如何使用elasticsearch数据源获取grafana中字段的每个不同值的最后一个条目

dbf7pr2w  于 2021-06-14  发布在  ElasticSearch
关注(0)|答案(2)|浏览(673)

我有一个elasticsearch索引,其中包含以下文档:

{
  "_source": {
    "category": 1,
    "value": 10,
    "utctimestamp": "2020-10-21T15:32:00.000+00:00"
  }
}

在grafana中,我可以通过以下查询检索最近事件的值:

现在,我想得到每个不同值的最新文档的最大值 category 在给定的时间范围内。这意味着如果我的索引中有以下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(如果有第三个类别,则其最后一个值也应包含在最大值中)。
有可能吗?

daupos2t

daupos2t1#

感谢@val在sum over top点击聚合中的出色查询,您的查询将如下所示:

{
  "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"
      }
    }
  }
}
ryevplcw

ryevplcw2#

最后,我在elasticsearch和grafana之间创建了一个带有restapi的中间件服务,它可以向elasticsearch发出所有定制请求(比如@saeednasehi的答案中给出的请求),我使用json数据源插件从grafana查询中间件

相关问题