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

如何修改Elasticsearch查询统计Top5 API各HTTP状态码的占比

Elasticsearch 按API统计HTTP状态码占比的修改方案

你可以通过在现有聚合逻辑基础上新增bucket_script管道聚合实现状态码占比计算,修改后的完整查询如下:

{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "@timestamp": {
              "from": "now-15m",
              "to": "now",
              "include_lower": true,
              "include_upper": true,
              "boost": 1
            }
          }
        }
      ],
      "adjust_pure_negative": true,
      "boost": 1
    }
  },
  "aggregations": {
    "Url": {
      "terms": {
        "field": "data.url.keyword",
        "size": 5,
        "min_doc_count": 1,
        "shard_min_doc_count": 0,
        "show_term_doc_count_error": false,
        "order": [
          {
            "_count": "desc"
          },
          {
            "_key": "asc"
          }
        ]
      },
      "aggregations": {
        "Status": {
          "terms": {
            "field": "data.response.status",
            "size": 5,
            "min_doc_count": 1,
            "shard_min_doc_count": 0,
            "show_term_doc_count_error": false,
            "order": [
              {
                "_count": "desc"
              },
              {
                "_key": "asc"
              }
            ]
          },
          "aggregations": {
            "status_percent": {
              "bucket_script": {
                "buckets_path": {
                  "status_count": "_count",
                  "total_count": "_parent"
                },
                "script": "Math.round((params.status_count / params.total_count) * 10000) / 100"
              }
            }
          }
        }
      }
    }
  }
}

修改说明

  • 新增status_percent管道聚合,通过buckets_path获取当前状态码的请求数、对应API的总请求数,直接计算得到百分比值,脚本逻辑默认保留两位小数,可根据需求调整精度
  • 原有查询逻辑完全保留,不会影响Top5 API、状态码计数的获取

结果拼接

查询返回后,遍历每个URL聚合桶,提取各状态码的key、doc_count、status_percent.value三个字段,按你需要的格式拼接即可。以你给出的返回结果为例,拼接后输出为:

API               
/account/me  200: 3261(92.77%) 400: 254(7.23%)
/PlanDetails 200: 3376(99.73%)
/evaluation  200: 3282(100%)
/user/me     200: 3205(100%)
/user        200: 3055(100%)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 11:39:03