首页 > 解决方案 > 如何使用 Vega-Lite 仅绘制最新时间的文档?

问题描述

我有一个带有时间字段的索引 - “时间”,对于每个“时间”值,都有多个文档。我只想展示最近一次的结果。我该怎么做?有没有办法计算所有文档的时间字段的最大值,然后根据这个值应用过滤器?

这是代码示例:

{
  $schema: https://vega.github.io/schema/vega-lite/v2.json

  data: {
    data: table
    url: {
      %context%: true
      %timefield%: Time
      index: data*
      body: {
        size: 10000
        _source: ["X", "Y"]
      }
    }
    format: {property: "hits.hits"}
  }
  mark: {type: "square", filled: true, size: 800 }
encoding: {
    x: {
      field: "_source.X"
      type: quantitative
      axis: {title: "X"}
    }
    y: {
      field: "_source.Y"
      type: quantitative
      axis: {title: "Y"}
    }  
}
}

我尝试了这段代码,但它仍然无法正常工作。我猜我的语法不正确?

{
  "$schema": "https://vega.github.io/schema/vega-lite/v2.json",
  "data": {
    "data": "table",
    "url": {
      "%context%": true,
      "%timefield%": "Time",
      "index": "data*",
      "body": {
        "size": 10000,
        "aggs": {
          "time_field": {
            "terms": {"field": "Time", "size": 1, "order": {"_key": "desc"}},
            "aggs": {
              "x_Field": {"terms": {"field": "X", "size": 10000}},
              "y_Field": {"terms": {"field": "Y", "size": 10000}}
            }
          }
        }
      }
    },
    "format": {"property": "aggregations.category.buckets[0].x_Field.buckets"}
        "format": {"property": "aggregations.category.buckets[0].y_Field.buckets"}

  },
  "mark": {"type": "square", "filled": true, "size": 800},
  "encoding": {
    "x": {"field": "x_Field", "type": "quantitative", "axis": {"title": "X"}},
    "y": {"field": "y_Field", "type": "quantitative", "axis": {"title": "Y"}}
  }
}

标签: elasticsearchkibanavega-litegraph-visualization

解决方案


您可以按大小为 1 的降序对时间字段进行排序,这将为您提供属于最新时间的文档,然后您需要根据 elasticsearch 输出更改格式。下面是弹性搜索的示例代码:

 "body": {
    "size": 10000,
    "aggs": {
        "time_field": {
            "terms": {
                "field": "Time",
                "size": 1,
                "order": {
                    "_key": "desc"
                }
            },
            "aggs": {
                "x_Field": {
                    "terms": {
                        "field": "x",
                        "size": 10000
                    }
                }
            }
        }
    }
}

编辑:使用以下格式后,您可以在 key 中获取展平的 x 字段数据。

  "format": {
        "property": "aggregations.category.buckets[0].x_Field.buckets"
    }

推荐阅读