Elasticsearch Top hits聚合查询nested字段过滤未生效问题求助
问题根因
你外层的nested查询仅负责筛选「包含至少1个visible=true子项的父文档」,不会作用到nested聚合的子项遍历逻辑里。当进入items的nested聚合上下文后,会遍历命中父文档下的所有子项,自然就会带出不符合过滤条件的子项。
解决方案
在nested聚合下新增一层filter聚合,把items.visible=true的过滤条件放到聚合内部执行,过滤掉不符合条件的子项后再执行top_hits查询即可。
修改后的查询语句如下:
POST /test_index/_search?pretty=true&typed_keys=true { "aggs": { "by_items": { "nested": { "path": "items" }, "aggs": { "filter_visible": { "filter": { "term": { "items.visible": true } }, "aggs": { "top_item_hits": { "top_hits": { "from": 0, "size": 20, "sort": [ { "items.text": { "order": "asc" } } ] } } } } } } }, "size": 0, "_source": false }
如果数据量较大,也可以保留你原查询外层的nested query,预先过滤掉不存在visible=true子项的父文档,减少聚合计算量,不会影响最终返回结果。
内容的提问来源于stack exchange,提问作者core
相关产品推荐
相关产品推荐

