多个索引的Elasticsearch计数

Elasticsearch counts of multiple indices

我正在创建一个报告来比较数据库中的实际计数与索引记录。

我有三个索引 index1、index2 和 index3

要获取单个索引的计数,我使用以下 URL

http://localhost:9200/index1/_count?q=_type:invoice

=> {"count":50,"_shards":{"total":5,"successful":5,"failed":0}}

对于多个索引:

http://localhost:9200/index1,index2/_count?q=_type:invoice

=> {"count":80,"_shards":{"total":5,"successful":5,"failed":0}}

现在计数已加起来,我希望它按索引分组,我怎样才能通过特定字段的过滤器组 得到这样的输出:

{"index1_count":50,"index2_count":50,"approved":10,"rejected":40 ,"_shards":{"total":5,"successful":5,"failed":0}}

您可以使用 _search?search_type=count 并根据 _index 字段进行聚合以区分索引:

GET /index1,index2/_search?search_type=count
{
  "aggs": {
    "by_index": {
      "terms": {
        "field": "_index"
      }
    }
  }
}

结果会是这样的:

"aggregations": {
      "by_index": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "index1",
               "doc_count": 50
            },
            {
               "key": "index2",
               "doc_count": 80
            }
         ]
      }
   }