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

如何编写Elasticsearch查询统计指定API的状态码数量?

Elasticsearch 等效SQL查询实现

你需要的Elasticsearch DSL查询语句如下,完全对应你给出的SQL逻辑:

GET /Index-b2b-api/_search
{
  "size": 0,  // 不需要返回原始文档,只看聚合结果
  "query": {
    "term": {
      "api-proxy-name.keyword": "some-b2b-api"  // 精确匹配字段值,text类型字段需加.keyword后缀
    }
  },
  "aggs": {
    "group_by_status": {
      "terms": {
        "field": "status_code"  // 按status_code分组
      },
      "aggs": {
        "count_records": {
          "value_count": {
            "field": "_id"  // 统计每组文档数量,等效SQL的count(1)
          }
        }
      }
    }
  }
}

关键部分说明:

  • size: 0:仅获取聚合统计结果,不返回具体文档,提升查询效率。
  • term查询:用于精确匹配api-proxy-name的值,若字段为text类型,必须加.keyword后缀(ES默认给text字段生成keyword子字段);若字段本身是keyword类型,直接写字段名即可。
  • terms聚合:对应SQL的GROUP BY status_code,按status_code的值分组。
  • value_count聚合:对应SQL的count(1),利用每个文档唯一的_id统计分组内的文档数量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:25:45