使用_msearch API执行多查询时,如何获取文档计数?
通过_msearch API获取文档计数的方法
当然可以,以下两种方法都能让你在_msearch请求内获取各查询的文档计数:
方法一:用
track_total_hits配合size:0
在每个子查询里设置size: 0(不返回具体文档,节省带宽),同时开启track_total_hits: true,这样返回结果的hits.total.value就是该查询匹配的精确文档数。示例请求:{"index": "your_index"} {"query": {"match_all": {}}, "size": 0, "track_total_hits": true} {"index": "another_index"} {"query": {"term": {"status": "active"}}, "size": 0, "track_total_hits": true}默认情况下,当匹配文档数超过10000时,Elasticsearch会返回近似值,
track_total_hits: true可以强制返回精确计数。方法二:借助聚合统计
给每个子查询添加value_count聚合,针对_id这类必存在的字段统计总数,也能得到准确的文档计数。示例:{"index": "your_index"} {"query": {"match_all": {}}, "size": 0, "aggs": {"total_docs": {"value_count": {"field": "_id"}}}}结果里的
aggregations.total_docs.value就是对应查询的文档数量。
这两种方法都不需要额外调用/_count API,完全在单个_msearch请求内完成多查询的计数需求。
内容的提问来源于stack exchange,提问作者daisy
相关产品推荐
相关产品推荐

