Elasticsearch查询文档总数


前言

在使用ES搜索的时候,或多或少都会面临查询数据总量的情况,下面介绍三种查询数据总量的方式。

其中,方案二解决了当结果数据总量超过1w时,由于ES默认设置(max_result_window:10000,出于性能问题考虑,用户也不想放开这个限制),只能返回命中数等于1w的问题。

方案一

查询全部索引下的文档总数:

GET /_cat/count

查询某个索引下的文档总数(为索引名):

GET /_cat/count/

官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-count.html

方案二

track_total_hits" 属性设置为 true(为索引名)

GET /_search
{
  "track_total_hits": true,
  // ????以下可以为任意检索条件
  "query": {
    "match_all" : {
    }
  }
}

官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-your-data.html

方案三(不推荐)

此命令是查询索引状态的,当然也包含了每个索引下的文档数量。但是在部分情况下,是不够准确的,因为这个数量包含了隐藏的嵌套文档。参考官方文档的解释:
These metrics are retrieved directly from Lucene, which Elasticsearch uses internally to power indexing and search. As a result, all document counts include hidden nested documents.
To get an accurate count of Elasticsearch documents, use the cat count or count APIs.

GET /_cat/indices
GET /_cat/indices/

官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-indices.html