You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构建ElasticSearch统计查询以按索引返回统计结果

按索引分组统计匹配前缀的记录数

你原来的查询用于统计所有匹配索引的总记录数:

GET /index-*/_count
{
  "query": {
    "match_phrase": {
      "user.username": "prefix-*"
    }
  }
}

返回结果为所有索引的总计数:

{
  "count": 44263306,
  "_shards": {
    "total": 196,
    "successful": 196,
    "skipped": 0,
    "failed": 0
  }
}

要按每个索引单独返回统计数,直接使用Elasticsearch的聚合功能即可——通过_index字段分组统计匹配记录,查询语句如下:

GET /index-*/_search
{
  "size": 0,  // 不返回具体文档,仅返回聚合统计结果
  "query": {
    "match_phrase_prefix": {  // 用该类型更适配前缀匹配场景,替代带通配符的match_phrase
      "user.username": "prefix-"
    }
  },
  "aggs": {
    "per_index_counts": {
      "terms": {
        "field": "_index",
        "size": 1000  // 设置足够大的数值,确保覆盖所有匹配的索引
      }
    }
  }
}

返回结果示例

聚合结果会清晰展示每个索引对应的匹配记录数:

{
  "took": 120,
  "timed_out": false,
  "_shards": {
    "total": 196,
    "successful": 196,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 44263306,
      "relation": "eq"
    },
    "max_score": null,
    "hits": []
  },
  "aggregations": {
    "per_index_counts": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "index-1",
          "doc_count": 123456
        },
        {
          "key": "index-2",
          "doc_count": 789012
        },
        {
          "key": "index-3",
          "doc_count": 345678
        }
      ]
    }
  }
}

转换为你需要的格式

从聚合结果的buckets中提取数据,可快速转换成你想要的格式:

表格格式

index_namecount
index-1123456
index-2789012
index-3345678

JSON数组格式

[
  {"indexName": "index-1", "count": 123456},
  {"indexName": "index-2", "count": 789012},
  {"indexName": "index-3", "count": 345678}
]

内容的提问来源于stack exchange,提问作者user11058144

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 05:17:41