elasticsearch - 如何使用 elasticsearch 获取嵌套字段的所有值?
问题描述
我能够使用弹性搜索 6.8 中的聚合查询获取数据库中文本字段的所有值:
{
aggs: {
values: {
terms: { field: 'City.keyword', size: 200 },
},
},
size: 0,
};
我正在尝试对嵌套字段做同样的事情。
下面是一个文本字段 (City) 和一个嵌套字段 (Cooling) 的示例
"City": "Fredericksburg",
"Cooling": [
{
"key": "Fuel",
"value": "Electric"
},
{
"key": "Central Air",
"value": "Y"
},
{
"key": "Central A/C",
"value": "true"
}
],
这是我一直在参考的文档: https ://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-aggregations-bucket-terms-aggregation.html
这是相关的映射:
{
"listings:366": {
"mappings": {
"_default_": {
"_all": {
"enabled": false
},
"dynamic_templates": [
...
{
"Cooling": {
"path_match": "Cooling.*",
"mapping": {
"type": "text"
}
}
},
...
],
"properties": {
...
"Cooling": {
"type": "nested"
},
...
}
},
"listings": {
"_all": {
"enabled": false
},
"dynamic_templates": [
...
{
"Cooling": {
"path_match": "Cooling.*",
"mapping": {
"type": "text"
}
}
},
...
],
"properties": {
...
"Cooling": {
"type": "nested",
"properties": {
"key": {
"type": "text"
},
"value": {
"type": "text"
}
}
},
}
}
}
}
}
解决方案
如果Cooling
是类型,那么您可以通过首先将聚合嵌套在顶级聚合nested
中来实现您想要的,以便“深入”Cooling 嵌套文档:terms
nested
{
"size": 0,
"aggs": {
"cooling": {
"nested": {
"path": " Cooling"
},
"aggs": {
"values": {
"terms": {
"field": "Cooling.key", <--- make sure this field is mapped as keyword
"size": 200
}
}
}
}
}
}
更新
您的映射需要更改为:
"properties": {
...
"Cooling": {
"type": "nested",
"properties": {
"key": {
"type": "keyword" <--- change this
},
"value": {
"type": "text"
}
}
},
}