How to perform multiple aggregation on an object i

2019-07-28 20:47发布

问题:

I want to perform date histogram query on my Elasticsearch data which is of the format:

datetime,field_obj and field_obj has three fields in it: a,b,c

Alongside date histogram aggregation, I want to find the average of field_obj i.e avg(field_a), avg(field_b), avg(field_c) also. I tried working it out like this:

    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"}}},
                         }}
         })  

However, this query only yields an average of field_c. All the other averages are getting overridden.

回答1:

Good start! You need to do it like this and it will work:

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"
          }
        }
      }
    }
  }
})