Skip to content

聚合分析

ES 的另一半能力是聚合:不返回文档,返回统计结果。日志分析里的「按小时统计错误数」、电商里的「各价格区间商品数」、监控大盘的「P99 延迟」,全是聚合。这篇把聚合的类型体系、组合方式和生产环境的坑讲清。

一、聚合的结构

一次聚合请求:

bash
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '
{
  "size": 0,
  "query": { "term": { "on_sale": true } },
  "aggs": {
    "by_brand": {
      "terms": { "field": "brand" }
    }
  }
}'

返回:

json
{
  "hits": { "total": { "value": 100, "relation": "eq" }, "hits": [] },
  "aggregations": {
    "by_brand": {
      "buckets": [
        { "key": "logitech", "doc_count": 30 },
        { "key": "razer", "doc_count": 25 }
      ]
    }
  }
}

三个必知约定:

  • size: 0:聚合场景不返回文档,只返回统计。不设 size 会白返回 10 篇文档原文,浪费带宽;
  • 聚合和查询共享 query:聚合只在 query 命中的文档范围内统计,可以同时返回 hits 和 aggs;
  • aggs 嵌套:一个聚合里套子聚合,逐层下钻,这是 ES 分析能力的核心。

二、Metric 聚合:算一个数

对文档集合算统计值:

bash
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '
{
  "size": 0,
  "aggs": {
    "price_stats": { "stats": { "field": "price" } },
    "price_avg": { "avg": { "field": "price" } },
    "price_max": { "max": { "field": "price" } },
    "price_sum": { "sum": { "field": "price" } },
    "price_cardinality": { "cardinality": { "field": "brand" } }
  }
}'
聚合返回
avg / min / max / sum平均/最小/最大/总和
statscount、min、max、avg、sum 五合一
value_count字段有值的文档数(null 不算)
cardinality近似去重计数,见下

2.1 cardinality 的精度问题

json
{ "cardinality": { "field": "user_id" } }

基于 HyperLogLog++ 算法,近似值,不是精确去重:

json
{ "cardinality": { "field": "user_id", "precision_threshold": 10000 } }
  • 默认精度阈值下,千万级去重的误差率通常在 1%~5%;
  • precision_threshold 最高 40000,越高越准、内存开销越大(每个阈值档位内存翻倍级增长);
  • 要精确计数的场景(对账、计费)不能用 cardinality,用脚本聚合或业务库计数。

UV 统计、去重设备数这类容忍误差的场景放心用,TB 级数据算 UV 是它的主场。

2.2 百分位:延迟分析的标配

json
{
  "percentiles": {
    "field": "response_time",
    "percents": [50, 90, 95, 99]
  }
}

P50/P90/P95/P99 一次算出。也是近似算法(TDigest),误差可控。监控场景的「P99 延迟突增」比平均值敏感得多——平均值被长尾平均掉了,P99 不会。

三、Bucket 聚合:分组

按字段值分组,每组一个 bucket:

3.1 terms:按字段值分组

bash
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '
{
  "size": 0,
  "aggs": {
    "by_brand": {
      "terms": {
        "field": "brand",
        "size": 10,
        "order": { "_count": "desc" }
      }
    }
  }
}'

返回 doc_count 最高的前 10 个品牌。

精度陷阱:terms 聚合默认只返回每个分片的 top N,协调节点归并后再取 top N。单分片数据量大时,全局 top N 可能有误差(某个品牌在两个分片都排第 11,归并后能进前 10,但单分片视角都看不到)。要精确结果:

json
{
  "aggs": {
    "by_brand": {
      "terms": { "field": "brand", "size": 10, "show_term_doc_count_error": true }
    }
  }
}

show_term_doc_count_error: true 会返回每个 bucket 的 doc_count_error_upper_bound——理论最大误差。不为 0 说明这个计数是近似的。

分片数少(1~3 个)时误差几乎为 0,分片多的大索引要注意。精确分组计数的终极方案是 size 足够大或对聚合字段做单分片索引。

3.2 date_histogram:按时间分桶

日志分析的核心聚合:

bash
curl -X POST "localhost:9200/logs/_search" -H 'Content-Type: application/json' -d '
{
  "size": 0,
  "query": { "range": { "@timestamp": { "gte": "now-24h" } } },
  "aggs": {
    "per_hour": {
      "date_histogram": {
        "field": "@timestamp",
        "fixed_interval": "1h",
        "format": "yyyy-MM-dd HH:mm",
        "time_zone": "+08:00"
      }
    }
  }
}'

按小时分桶,返回每小时的文档数。空桶也会补(默认 min_doc_count: 0 才补,设 1 则跳过空桶——画折线图要连续的话用 0)。

fixed_interval 用 1h/1d/30m 这类固定单位,calendar_interval 用 1M/1y 这种自然月年(一个月 30 天还是 31 天它按日历算)。配置时间用 fixed,按月统计用 calendar。

时区:默认 UTC,中国场景 time_zone: "+08:00",否则「今天 0 点」的桶是北京时间早上 8 点。

3.3 range / filter / nested:其他分桶

bash
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '
{
  "size": 0,
  "aggs": {
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "to": 100 },
          { "from": 100, "to": 300 },
          { "from": 300 }
        ]
      }
    },
    "out_of_stock": {
      "filter": { "term": { "stock": 0 } },
      "aggs": {
        "avg_price": { "avg": { "field": "price" } }
      }
    }
  }
}'
  • range:数值/日期区间分桶,电商价格筛选计数用;
  • filter:单条件过滤后统计,等价于一次子查询;
  • nested:嵌套对象的聚合,见《数据关系与嵌套》。

四、子聚合:逐层下钻

聚合的真正威力在嵌套:

bash
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '
{
  "size": 0,
  "aggs": {
    "by_brand": {
      "terms": { "field": "brand" },
      "aggs": {
        "avg_price": { "avg": { "field": "price" } },
        "max_price": { "max": { "field": "price" } }
      }
    }
  }
}'

按品牌分组,每组算均价和最高价。三层嵌套也合法:按品牌 → 按价格区间 → 算库存总和。

下钻时注意每层 size:外层 size: 10 只保留 10 个品牌,子聚合只在这 10 个组内算。想全量分析就调大外层 size,代价是内存和耗时线性涨。

五、管道聚合:对聚合结果再计算

管道聚合的输入是另一个聚合的输出,用于二次计算:

bash
curl -X POST "localhost:9200/logs/_search" -H 'Content-Type: application/json' -d '
{
  "size": 0,
  "aggs": {
    "per_hour": {
      "date_histogram": { "field": "@timestamp", "fixed_interval": "1h" },
      "aggs": {
        "error_count": { "filter": { "term": { "level": "ERROR" } } },
        "error_rate": {
          "bucket_script": {
            "buckets_path": { "errors": "error_count._count" },
            "script": "params.errors / 100.0"
          }
        },
        "cumulative": {
          "cumulative_sum": { "buckets_path": "_count" }
        }
      }
    }
  }
}'

常用管道聚合:

聚合作用
cumulative_sum累计求和,累计曲线
derivative环比(相邻桶差值),算增长率
moving_fn滑动窗口平均,平滑曲线
bucket_script自定义脚本计算,误差率这类指标
bucket_sort对 bucket 排序/分页(terms 排序的补充)
bucket_selector按条件过滤 bucket,只要 top N

bucket_script 用 Painless 脚本,buckets_path 引用其他聚合的结果。错误率、转化率这类「两个统计值的组合」全靠它。

六、聚合的性能与调优

聚合是重操作,比搜索重得多。优化点:

  1. size: 0:再说一遍,纯聚合场景不返回文档。
  2. 缩小 query 范围:聚合范围 = query 命中范围。时间范围过滤加上,别全索引聚合。
  3. fielddata vs doc_values:聚合字段用 keyword/数值(有 doc_values),text 字段聚合必开 fielddata,内存炸弹。
  4. 高基数 terms 聚合:品牌几千个还行,用户 ID 千万级别的 terms 聚合直接打爆。要么 size 限制 + shard_size 调优,要么预计算(rollup)。
  5. search_after 聚合分页:terms 聚合超过 size 的部分用 bucket_sort 的 from 翻页,配合 key 排序保证稳定。
json
{
  "aggs": {
    "by_user": {
      "terms": {
        "field": "user_id",
        "size": 1000,
        "shard_size": 2000,
        "order": { "_key": "asc" }
      },
      "aggs": {
        "sort_paging": {
          "bucket_sort": { "from": 1000, "size": 1000 }
        }
      }
    }
  }
}

shard_size 是每个分片预取的 bucket 数(提高归并精度,默认 = size),翻页场景建议 size × 1.5~2。

  1. 超时保护:聚合请求带 timeout,避免慢聚合拖垮集群:
bash
curl -X POST "localhost:9200/products/_search" -H 'Content-Type: application/json' -d '
{
  "timeout": "5s",
  "aggs": { "big_terms": { "terms": { "field": "user_id" } } }
}'
  1. rollup / transform:周期性预聚合。日志类数据的日报、周报不需要实时扫全量,用 Transform 或 Rollup 提前算好存成索引,查询直接查汇总索引。大数据量聚合的正解。

七、常见坑汇总

  1. 聚合返回的不是精确值:terms 的单分片 top N + cardinality 的近似,都是设计取舍。show_term_doc_count_error 看误差边界。
  2. 聚合字段是 text:直接报 fielddata 错。换 .keyword 子字段。
  3. date_histogram 时区错位:默认 UTC,中国 +8。桶边界差 8 小时,日报全乱。
  4. 子聚合外层 size 太小:以为在分析全量,实际只在 top N 组内算。
  5. 聚合不带 query 过滤:全索引聚合,慢且结果没意义。
  6. 忘了 size: 0:聚合 + 10 篇文档原文,响应体白白胖几 KB。 Kibana 的 Discover 也会提示你。
  7. 对持续写入的索引做重聚合:聚合期间数据在变,前后两次结果不一致。要么容忍,要么用 PIT(point in time)固定数据视图。

聚合讲完,搜索和统计的能力都齐了。下一篇《分布式搜索与深分页》讲这些查询在集群里怎么执行,以及深分页这个老大难。

CTO Plus技术栈 Version 1.0.20261024-12