Elasticsearch如何实现差值聚合:计算单小时volume较上一小时增量
可以实现,针对这种累计型(cumulative)监控指标的小时增量计算,推荐以下两种实现方式:
方案1:使用Elasticsearch管道聚合原生计算
你可以结合date_histogram分桶+max聚合取每个小时的累计最大值+serial_diff管道聚合计算差值,查询示例如下:
{ "index": "cm", "size": 0, "pretty": true, "body": { "query": { "bool": { "must": [ { "match": { "project_id": "75ebb9556f8c4e36b0d3e722a57ff3bb" } }, { "range": { "timestamp": { "gte": "now-2H", "lt": "now" } } } ] } }, "aggs": { "names": { "terms": { "field": "name" }, "aggs": { "hourly_bucket": { "date_histogram": { "field": "timestamp", "calendar_interval": "hour", "format": "yyyy-MM-dd HH:mm:ss" }, "aggs": { "cumulative_volume": { "max": { "field": "volume" } } } }, "hourly_increment": { "serial_diff": { "buckets_path": "hourly_bucket>cumulative_volume", "lag": 1 } } } } } } }
返回结果中每个指标的hourly_increment值就是你需要的小时增量,即当前小时累计值减去上一小时累计值的结果。
注意:
- 累计型指标随时间递增,用
max取每个小时的最大值作为该小时结束时的累计值,比sum统计更准确- 如果遇到实例重启、指标重置导致差值为负的情况,可在应用层做兜底处理,取
max(增量值, 0)作为最终结果即可
方案2:应用层手动计算
如果你使用的Elasticsearch版本不支持serial_diff聚合,也可以手动实现逻辑:
- 按近2小时范围查询,按指标名+小时分组,拿到每个指标每小时的累计最大值
- 在代码中遍历每个指标的两个小时累计值,用当前小时值减去上一小时值得到增量
内容的提问来源于stack exchange,提问作者cybercoder
相关产品推荐
相关产品推荐

