Elasticsearch多索引查询时如何在同一DSL中限制单索引返回结果数量
Elasticsearch多索引查询限制单索引返回结果数方案
要实现同一份查询DSL中分别限制每个索引的返回结果数,可通过按索引字段分组+top_hits聚合的方式实现,修改后的查询DSL如下:
POST http://localhost:9200/componenttypeindex%2Cprojecttypeindex/Componenttype%2CProjecttype/_search?pretty=true&typed_keys=true { "size": 0, "query": { "bool": { "should": [ { "bool": { "filter": [ { "term": { "_index": { "value": "componenttypeindex" } } } ], "must": [ { "multi_match": { "fields": [ "Componentname", "Summary^1.1" ], "operator": "or", "query": "test" } } ] } }, { "bool": { "filter": [ { "term": { "_index": { "value": "projecttypeindex" } } } ], "must": [ { "multi_match": { "fields": [ "Projectname", "Summary^0.3" ], "operator": "or", "query": "test" } } ] } } ] } }, "aggs": { "group_by_index": { "terms": { "field": "_index", "size": 10 }, "aggs": { "each_index_top_hits": { "top_hits": { "size": 5, // 此处调整每个索引最多返回的结果条数 "sort": [ {"_score": {"order": "desc"}} // 可自定义索引内的排序规则 ] } } } } } }
参数说明
- 全局
size设置为0:不需要返回全局匹配的原始文档列表,仅获取聚合结果即可减少不必要的性能开销 group_by_index聚合:按内置字段_index对命中文档做分组,自动拆分不同索引的匹配结果each_index_top_hits聚合:嵌套在分组聚合内的top_hits聚合,其中的size参数就是每个索引最多返回的结果数,可根据业务需求灵活调整
如果需要给不同索引设置不同的返回条数,也可以直接定义多个独立的top_hits聚合,每个聚合单独添加索引过滤规则和对应返回条数即可。
内容的提问来源于stack exchange,提问作者marcus
相关产品推荐
相关产品推荐

