主题
嵌套与管道聚合
Elasticsearch 支持多级嵌套聚合和基于聚合结果的管道聚合,能够完成复杂的数据统计和进一步的结果处理。
1. 嵌套聚合(Nested Aggregation)
通过在桶聚合内部嵌套其他聚合,实现多维度、多层次的数据分组统计。
示例:按类别分组后统计平均价格
json
GET /my-index/_search
{
"size": 0,
"aggs": {
"by_category": {
"terms": {
"field": "category.keyword"
},
"aggs": {
"average_price": {
"avg": {
"field": "price"
}
}
}
}
}
}
2. 管道聚合(Pipeline Aggregation)
基于已有聚合结果进行进一步计算,如计算差值、移动平均等。
示例:计算销售额月环比增长率
json
GET /my-index/_search
{
"size": 0,
"aggs": {
"sales_over_time": {
"date_histogram": {
"field": "sale_date",
"calendar_interval": "month"
},
"aggs": {
"monthly_sales": {
"sum": {
"field": "sales"
}
},
"sales_derivative": {
"derivative": {
"buckets_path": "monthly_sales"
}
}
}
}
}
}
3. 常见管道聚合类型
derivative
:计算相邻桶的差值moving_avg
:移动平均cumulative_sum
:累积和bucket_script
:基于脚本的自定义计算
4. 注意事项
- 管道聚合依赖于父聚合的结果,需合理设计嵌套结构
- 管道聚合无法直接作用于文档,需要先聚合形成桶
- 使用管道聚合时要关注性能影响,避免复杂计算阻塞查询
掌握嵌套与管道聚合,能帮助你构建复杂多维的数据分析模型,实现精准业务洞察。