前言
在使用ES搜索的時候,或多或少都會面臨查詢數據總量的情況,下面介紹三種查詢數據總量的方式。
其中,方案二解決了當結果數據總量超過1w時,由於ES默認設置(max_result_window:10000,出於性能問題考慮,用戶也不想放開這個限制),只能返回命中數等於1w的問題。
方案一
查詢全部索引下的文檔總數:
GET /_cat/count
查詢某個索引下的文檔總數(<target>為索引名):
GET /_cat/count/<target>
官方文檔:https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-count.html
方案二
將 track_total_hits" 屬性設置為 true(<target>為索引名)
GET <target>/_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/<target>
官方文檔:https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-indices.html