zaartix
zaartix

Reputation: 11

Elasticsearch, group by field and calculate average value for another field

Mapping:

player_id: int
stat_date: date
some_param: int

I need to calculate average value for "some_param" per each player_id used row with max "stat_date" in case of several rows with same player_id.

So i need average value for last date for all players

This snippet it not working because of "Aggregator [average_val] of type [avg] cannot accept sub-aggregations"

get test/test/_search
{
  "size":0,
  "aggs": {
    "average_val":{
      "avg": {
        "field": "some_param"
      },
      "aggs": {
        "by_player": {
          "terms": { "field" : "player_id" },
          "aggs" : {
              "by_date" : { 
                "max" : { "field" : "stat_date" } 
              }
          }
        }
      }
    }
  }
}

Simpliest way is use simple avg

get test/test/_search
{
  "size":0,
  "aggs": {
    "averages": {
      "avg": {
        "field": "some_param"
      }
    }
  }
}

But i need to calc avg player "some_param" only for last stat dates.

Upvotes: 1

Views: 1417

Answers (1)

Fei
Fei

Reputation: 2006

I think you would just need to reverse the order of your aggregation. Put avg aggregation in the deepest aggregation and it should work fine.

There are two major types of aggregation. Avg is a Metrics Aggregation and it outputs metrics (numbers). You would need to put Bucket Aggregations ( like terms aggregation) in the outside and do metrics aggregations for their output.

Upvotes: 2

Related Questions