我试图了解如何使用常规或嵌套字段的嵌套和常规过滤器动态构建聚合,因此,我的最终查询看起来像下面的代码,如果可以简化为两个级别(第一级过滤器),那就太好了,第二级术语查询)
{
"aggs": {
"city": {
"nested": {
"path": "locations"
},
"aggs": {
"city": {
"filter": {
"bool": {
"must": [
{
"terms": {
"locations.country.id": [
"4"
]
}
}
]
}
},
"aggs": {
"city": {
"reverse_nested": {},
"aggs": {
"city": {
"filter": {
"bool": {
"must": [
{
"terms": {
"category.id": [
"24"
]
}
}
]
}
},
"aggs": {
"city": {
"nested": {
"path": "locations"
},
"aggs": {
"city": {
"terms": {
"field": "locations.city.id",
"size": 1000
},
"aggs": {
"source": {
"top_hits": {
"size": 1,
"_source": {
"includes": [
"locations.city.id",
"locations.city.names"
]
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
我正在尝试简化 Elasticsearch 的困难查询
为了简化 Elasticsearch 聚合查询,您可以利用 Elasticsearch 的嵌套聚合和术语聚合。这是您查询的简化版本:
{
"aggs": {
"cities": {
"nested": {
"path": "locations"
},
"aggs": {
"country_filter": {
"filter": {
"terms": {
"locations.country.id": ["4"]
}
},
"aggs": {
"category_filter": {
"filter": {
"terms": {
"category.id": ["24"]
}
},
"aggs": {
"city_terms": {
"terms": {
"field": "locations.city.id",
"size": 1000
},
"aggs": {
"top_city_hits": {
"top_hits": {
"size": 1,
"_source": {
"includes": ["locations.city.id", "locations.city.names"]
}
}
}
}
}
}
}
}
}
}
}
}
}
在此简化版本中: 我首先使用嵌套聚合来处理
"locations"
路径下的嵌套文档。
然后,我为 country ID
应用过滤器聚合,并在该过滤器中为 category ID
应用另一个过滤器。最后,我在 city IDs
上应用术语聚合,并包含 top_hits 聚合以从匹配文档中检索特定字段.这应该会为您提供与原始查询相同的结果,但形式更简单。