【问题标题】:How to get last entry for each distinct value of a field in Grafana with an Elasticsearch data source如何使用 Elasticsearch 数据源获取 Grafana 中字段的每个不同值的最后一个条目
【发布时间】:2020-10-21 15:47:43
【问题描述】:

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

{
  "_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 中)。

有可能吗?

【问题讨论】:

    标签: elasticsearch grafana


    【解决方案1】:

    感谢@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"
          }
        }
      }
    }
    

    【讨论】:

    • 谢谢你。我想没有办法直接在grafana的查询生成器中复制这个查询吗?我想避免创建另一个索引(存储此查询的结果),该索引会复制数据以仅用于在 grafana 中绘图。
    • 哦!对不起。我没有意识到你想要这个用于你的 grafana。让我看看!
    【解决方案2】:

    我最终在 Elasticsearch 和 Grafana 之间使用 REST API 创建了一个中间件服务,该服务可以向 Elasticsearch 发出所有自定义请求(如@saeednasehi 的答案中给出的请求),我使用 @ 查询来自 Grafana 的中间件987654321@

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-19
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      相关资源
      最近更新 更多