如何在Elasticsearch聚合后过滤最新时间戳超2天的x-location?
解决方案
可以实现这个需求,你需要在现有聚合中添加bucket_selector管道聚合,用来过滤掉最新时间戳早于2天的x-location分组。
修改后的查询代码如下:
GET /mypattern-*/_search { "size": 0, // 无需返回原始文档,仅获取聚合结果可提升查询效率 "query": { "bool": { "must": [ {"match": {"method": "GET"}}, { "range": { "timestamp": { "gte": "now-1M" } } } ] } }, "aggs": { "location_terms": { "terms": { "field": "x-location.keyword", "min_doc_count": 5000, // 按需求修正为文档数大于5000,原代码为500可按需调整 "size": 1000, "order": { "recent_timestamp": "desc" } }, "aggs": { "recent_timestamp": { "max": { "field": "timestamp" } }, "filter_recent_location": { "bucket_selector": { "buckets_path": { "latestTime": "recent_timestamp" }, "script": "params.latestTime >= params.twoDaysAgo", "params": { "twoDaysAgo": "now-2d" } } } } } } }
关键说明:
size: 0:只返回聚合结果,避免不必要的原始文档传输,优化查询性能bucket_selector管道聚合:通过检查每个x-location分组的最新时间戳(recent_timestamp),自动过滤掉时间戳早于2天前的分组- 日期参数
now-2d:直接使用Elasticsearch内置的日期表达式,无需手动计算具体时间戳
内容的提问来源于stack exchange,提问作者nolwww
相关产品推荐
相关产品推荐

