Elasticsearch:使用 count API 来获得所有文档的个数

1,065 阅读1分钟

在我开始使用 Elasticsearch 的时候,我希望获得给定查询的文档总数。比如我们想对数据进行分页显示。从 Elasticsearch 7.0之后,为了提高搜索的性能,在 hits 字段中返回的文档数有时不是最精确的数值。Elasticsearch 限制了最多的数值为10000。我们知道 Search API 提供的计数不准确,但后来我发现我可以通过 “track_total_hits” 参数获得这个结果。具体可以参考文章 “Elasticsearch:如何在搜索时得到精确的总 hits 数

然而,通过进一步研究,我发现了一种更简单的方法来获取查询的实际文档数。

使用 Count API,我可以从查询中获取文档总数。



1.  GET my_index/_count
2.  {
3.    "query": {
4.     "range": {
5.       "year": {
6.         "gte": 1991
7.       }
8.     }
9.    }
10.  }


在我们的示例中,我们将获得 1991 年之后发布的文档总数。



1.  {
2.    "count": 634,
3.    "_shards": {
4.      "total": 1,
5.      "successful": 1,
6.      "skipped": 0,
7.      "failed": 0
8.    }
9.  }


如你所见,响应大小紧凑,如果使用 Search API,它的结果则不同。另外,

这很好,因为通过网络传输的数据包较小,这对成本有积极影响。