我有一个包含这些文档的 elasticsearch 索引:
{
"_source": {
"category": 1,
"value": 10,
"utctimestamp": "2020-10-21T15:32:00.000+00:00"
}
}
在 Grafana 中,我可以使用以下查询检索最近事件的值:
现在,我想获取给定时间范围内 category
的每个不同值的最新文档的 MAX 值。
这意味着如果我的索引中有以下 3 个文档:
{
"_source": {
"category": 1,
"value": 10,
"utctimestamp": "2020-10-21T10:30:00"
}
},
{
"_source": {
"category": 2,
"value": 20,
"utctimestamp": "2020-10-21T10:20:00"
}
},
{
"_source": {
"category": 2,
"value": 30,
"utctimestamp": "2020-10-21T10:10:00"
}
}
我希望查询返回值 MAX(10, 20),即 20。因为类别 1 的最后一个文档的值为 10,而类别 2 的最后一个文档的值为 20。(如果有第三类,它的最后一个值也应该包含在 MAX 中)。
这可能吗?
最佳答案
感谢@val 在 Sum over top_hits aggregation 中的出色查询,您的查询将是这样的:
{
"size": 0,
"aggs": {
"category": {
"terms": {
"field": "category",
"size": 10
},
"aggs": {
"latest_quantity": {
"scripted_metric": {
"init_script": "params._agg.quantities = new TreeMap()",
"map_script": "params._agg.quantities.put(doc.utctimestamp.date, [doc.utctimestamp.date.millis, doc.value.value])",
"combine_script": "return params._agg.quantities.lastEntry().getValue()",
"reduce_script": "def maxkey = 0; def qty = 0; for (a in params._aggs) {def currentKey = a[0]; if (currentKey > maxkey) {maxkey = currentKey; qty = a[1]} } return qty;"
}
}
}
},
"max_quantities": {
"max_bucket": {
"buckets_path": "category>latest_quantity.value"
}
}
}
}
关于elasticsearch - 如何使用 Elasticsearch 数据源获取 Grafana 中字段的每个不同值的最后条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64467243/