如何使用Python在Elasticsearch中的对象上执行多次聚合?

时间:2018-06-21 06:29:32

标签: python elasticsearch aggregation elasticsearch-aggregation

我想对以下格式的Elasticsearch数据执行日期直方图查询:

datetime,field_obj和field_obj中包含三个字段:a,b,c

沿日期直方图聚合,我想查找field_obj的平均值,即avg(field_a),avg(field_b),avg(field_c)。 我尝试过这样解决问题:

    res = es.search(index="demo",body={"from": 0, "size": 0, "query": 
        {"match_all": {}}, "aggs": {
            "date_avg": {
                "date_histogram": {"field": "datetime","interval": "year"},
                    "aggs": {"avg_a": {"avg": {"field": "field.a"}}},
                    "aggs": {"avg_b": {"avg": {"field": "field.b"}}},
                    "aggs": {"avg_c": {"avg": {"field": "field.c"}}},
                         }}
         })  

但是,此查询仅产生field_c的平均值。所有其他平均值都被覆盖。

1 个答案:

答案 0 :(得分:1)

良好的开始!您需要这样做,这样才能正常工作:

res = es.search(index="demo",body={
  "from": 0,
  "size": 0,
  "query": {
    "match_all": {}
  },
  "aggs": {
    "date_avg": {
      "date_histogram": {
        "field": "datetime",
        "interval": "year"
      },
      "aggs": {
        "avg_a": {
          "avg": {
            "field": "field.a"
          }
        },
        "avg_b": {
          "avg": {
            "field": "field.b"
          }
        },
        "avg_c": {
          "avg": {
            "field": "field.c"
          }
        }
      }
    }
  }
})