Search code examples
elasticsearchdslquerydslelasticsearch-aggregation

Aggregation on a field and return the sum in elasticsearch


I am working to find the way to do aggregations on a field after filtering on an another filed. But, the Elastic search documentation is not easily understandable.

Lets say My Mapping:

[
  {
     a:'a1'
     b:'b1'
     c:120
     d:12
   },
  {
     a:'a2'
     b:'b1'
     c:170
     d:15
   }
  {
     a:'a3'
     b:'b2'
     c:128
     d:18
   }
  {
     a:'a4'
     b:'b1'
     c:158
     d:5
   }
] 

Required Aggregation:

Return the sum of field "c", by selecting the docs with "b" where b=b1 and d is less than 13

This is not my requirement, but the answer helps me in understanding the documentation.


Solution

  • Try this:

    POST index/_search
    {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "b": "b1"
              }
            },
            {
              "range": {
                "d": {
                  "lt": 13
                }
              }
            }
          ]
        }
      },
      "aggs": {
        "total": {
          "sum": {
            "field": "c"
          }
        }
      }
    }