桶聚合
本章定位:桶聚合是"GROUP BY"在 ES 中的等价物——将文档按某维度分组,对每个组执行指标聚合。
定义与作用
桶聚合(Bucket Aggregations) 将文档分配到不同的"桶"中:terms(按字段值分组)、range(按数值范围分组)、date_histogram(按时间间隔分组)、histogram(按数值间隔分组)。
完整示例:杨英的分组统计
POST /courses/_search
{
"size": 0,
"aggs": {
"by_category": {
"terms": { "field": "category.keyword", "size": 10 },
"aggs": {
"avg_price": { "avg": { "field": "price" } },
"avg_rating": { "avg": { "field": "rating" } }
}
},
"by_price_range": {
"range": {
"field": "price",
"ranges": [{ "to": 20000 }, { "from": 20000, "to": 40000 }, { "from": 40000 }]
}
}
}
}
小结
桶聚合三步骤:分组 → 统计 → 嵌套。terms 聚合在分布式环境可能有计数误差(doc_count_error_upper_bound),增大 shard_size 可减少。