Sum of a field after terms aggregation

Hi!

Given docs as the ones in the example below:

{ "id" : "1", "numValue": 9.7 }
{ "id" : "1", "numValue": 9.7 }
{ "id" : "1", "numValue": 9.7 }
{ "id" : "2", "numValue": 7 }
{ "id" : "2", "numValue": 7 }
{ "id" : "3", "numValue": 10 }

I'm trying to create a query that groups the docs by id like this (a simple terms aggregation):

{ "id" : "1", "numValue": 9.7 }
{ "id" : "2", "numValue": 7 }
{ "id" : "3", "numValue": 10 }

And then sums the "numValue": in this example 9.7 + 7 + 10.

I know I can get the first part done by using a max aggregation inside a terms, but I don't know how to get the total sum:

  "aggs": {
    "group_by_ID": {
      "terms": {
        "field": "ID",
        "min_doc_count": 1
      },
      "aggs": {
        "maxValue": {
          "max": {
            "field": "numvalue"
          }
        }
      }
    }
  }

I've also tried to add a sum aggregation that sums "maxValue", but the result is always 0.

A visualization would be a good option too, if it's easier that way, but it would need be compatible with Kibana 7.9.2.

Any help would be appreciated!

Kind regards,

Miguel

Kibana 7.9 is EOL and no longer supported. Please upgrade ASAP.

(This is an automated response from your friendly Elastic bot. Please report this post if you have any suggestions or concerns :elasticheart: )

Ok, then I would accept a solution even if it's not compatible with Kibana 7.9.2 hahaha

Hi @Miguel_Azorin

Try use sum buckets:

{
  "size": 0,
  "aggs": {
    "group_by_ID": {
      "terms": {
        "field": "id",
        "min_doc_count": 1
      },
      "aggs": {
        "maxValue": {
          "max": {
            "field": "numValue"
          }
        }
      }
    },
    "total": {
      "sum_bucket": {
        "buckets_path": "group_by_ID>maxValue"
      }
    }
  }
}
1 Like

Hi!

It works like a charm! Thank you very much!

Best regards,

Miguel

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.