我想在弹性搜索中汇总文档

时间:2020-05-09 20:12:41

标签: node.js elasticsearch kibana

在弹性搜索中,我有大量的文档,我想对文档进行分组并为其添加值。

样本文档:

[
{
"_id": "123",
"meter_id": "1001",
"voltage": "{
  "voltage": 50
}",
"date": 2020-05-09T06:03:56Z
}

{
"_id": "1234",
"meter_id": "1002",
"voltage": "{
  "voltage": 40
}",
"date": 2020-04-10T06:03:56Z
}
]

现在,我要匹配此集合的特定日期范围。例如,日期在2020-04-10到2020-05-09之间,并且符合此条件的文档应归为一个文档,该文档的通用meter_id 1001和所有文档的平均电压。

1 个答案:

答案 0 :(得分:-1)

POST _bulk
{"index":{"_index":"voltage","_type":"_doc"}}
{"meter_id":"1001","voltage":{"voltage":50},"date":"2020-04-09T06:03:56Z"}
{"index":{"_index":"voltage","_type":"_doc"}}
{"meter_id":"1001","voltage":{"voltage":60},"date":"2020-05-08T08:03:56Z"}
{"index":{"_index":"voltage","_type":"_doc"}}
{"meter_id":"1001","voltage":{"voltage":60},"date":"2020-05-01T08:03:56Z"}
GET voltage/_search
{
  "size": 0,
  "query": {
    "range": {
      "date": {
        "gte": "2020-04-10",
        "lte": "2020-05-09",
        "format": "yyyy-MM-dd"
      }
    }
  }, 
  "aggs": {
    "by_meter_id": {
      "terms": {
        "field": "meter_id.keyword"
      },
      "aggs": {
        "avg_voltage": {
          "avg": {
            "field": "voltage.voltage"
          }
        }
      }
    }
  }
}