How to perform multiple aggregation on an object in Elasticsearch using Python?

十年热恋 提交于 2019-12-11 12:11:46

问题


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


来源:https://stackoverflow.com/questions/50961773/how-to-perform-multiple-aggregation-on-an-object-in-elasticsearch-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!