はじめに
Logstash -> Elasticsearchへ連携する場合、ネストされたデータはデフォルトでArray datatypeになります。
このArray型は、例えば下記のclientデータのuserを検索する場合、 users.first == "山田" AND users.last == "花子"
という条件でもマッチしてしまいます。
要するに、Array型のネストされたデータはkeyとvalueの組み合わせでインデックスすることが出来ないんです。
clientデータサンプル
"client_name" : "テスト商社"
"users" : [
{
"first" : "山田",
"last" : "太郎"
},
{
"first" : "鈴木",
"last" : "花子"
}
]
}
データ型 | 条件 | 結果 | |
---|---|---|---|
1 | Array | first == "山田" AND last == "花子" | true |
2 | Nested | first == "山田" AND last == "花子" | false |
3 | Nested | first == "山田" AND last == "太郎" | true |
上記表の3のように、名字と名前が一致したときのみマッチするようにしたい!…
ということで次の章でNested datatypeにする方法を説明します。
やり方
Elasticsearchの機能であるインデックステンプレートを使います。Logstashでは下記のようにtemplateでインデックステンプレートが設定できます。
logstash.conf
...
output {
elasticsearch {
hosts => ["${ES_HOSTNAME}"]
index => "%{type}"
document_id => "%{type}_%{id}"
template => "/home/apps/logstash/customers_mapping.json"
template_name => "customers"
template_overwrite => true
}
}
customers_mapping.jsonのusers typeにnestedを指定します。
customers_mapping.json
{
"index_patterns": ["*"],
"settings": {
"number_of_shards": 1
},
"mappings": {
"_default_": {
"_source": {
"enabled": true
},
"properties": {
"users": {
"type": "nested",
"properties": {
"first": { "type": "keyword" },
"last": { "type": "keyword" }
}
}
}
}
}
}
以上、簡単にNested型に出来ました!