Elasticsearch でネストされたオブジェクトを使いたい場合に以下のようなマッピング1が必要になりますが、これを dynamic_templates で解決する方法です。
{
"cloth": {
"properties": {
"name": {
"type": "string",
"store": "yes",
"index": "analyzed"
},
"variation": {
"type": "nested",
"properties": {
"size": {
"type": "string",
"store": "yes",
"index": "not_analyzed"
},
"color": {
"type": "string",
"store": "yes",
"index": "not_analyzed"
}
}
}
}
}
}
dynamic_templates は以下のようになります。
Nested Type にしたいオブジェクト(variation) と、そのプロパティ(size や color) のテンプレートをそれぞれ用意するのがポイントです。
{
"template": "shop",
"mappings": {
"cloth": {
"dynamic_templates": [
{
"variation_template": {
"match": "variation",
"mapping": {
"type": "nested"
}
}
},
{
"variation_props_template": {
"path_match": "variation.*",
"mapping": {
"type": "{dynamic_type}",
"store": "yes",
"index": "not_analyzed"
}
}
}
]
}
}
}
実際にデータを投入しないとテンプレートが適用されないので(当たり前なんですが)適用前の状態で Nested Query を投げると豪快に QueryParsingException が発生するので注意が必要です。
誰もそんなことをやらないと思いますが、リリース直前に気づいたりすると結構ショックを受けるので念のため。
-
高速スケーラブル検索エンジン ElasticSearch Server 5.3 ネストされたオブジェクトの使い方 ↩