Sum aggregation on distinct values query

Hi, I am having trouble with my sum aggregation. I am using Elasticsearch [7.6.1] and I cant get the sum of each field, my data is the following:

POST test_2/_doc/1
{
  "gender": [
        {
            "name": "other",
            "value": 12
        },
        {
            "name": "male",
            "value": 20
        },
        {
            "name": "male",
            "value": 20
        },
        {
            "name": "other",
            "value": 9
        },
        {
            "name": "female",
            "value": 10
        } 
    ]
}

And I have implemented the following:

GET test_2/_search
    {
      "aggs": {
        "gender_terms": {
           "terms": {
              "field": "gender.name.keyword",
             "size": 10
           },
           "aggs": {
              "gender_name_value_sums": {
                 "sum": {
                    "field": "gender.value"
                 }
              }
           }
        }
      }
    }

The result I am expectin to recieve is the sum of each gender:
male: 40
female: 10
other: 22

But as a result I get the following:

"aggregations" : {
    "gender_terms" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "female",
          "doc_count" : 1,
          "gender_name_value_sums" : {
            "value" : 71.0
          }
        },
        {
          "key" : "male",
          "doc_count" : 1,
          "gender_name_value_sums" : {
            "value" : 71.0
          }
        },
        {
          "key" : "other",
          "doc_count" : 1,
          "gender_name_value_sums" : {
            "value" : 71.0
          }
        }
      ]
    }
  }

But why? I don't know why it is not showing me the correct vaules? :thinking:

Welcome!

Please format your code, logs or configuration files using </> icon as explained in this guide and not the citation button. It will make your post more readable.

Or use markdown style like:

```
CODE
```

This is the icon to use if you are not using markdown format:

There's a live preview panel for exactly this reasons.

Lots of people read these forums, and many of them will simply skip over a post that is difficult to read, because it's just too large an investment of their time to try and follow a wall of badly formatted text.
If your goal is to get an answer to your questions, it's in your interest to make it as easy to read and understand as possible.

Coming back to your question you probably need to use nested type for the gender field as everything is by default flattened.

Thanks @dadoonet ! I thought nested type was only implemented whe trying to obtain data from anothe API.

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