Search code examples
elasticsearchelasticsearch-aggregation

Elasticsearch - Query field against aggregation


I am exploring the ease of querying and aggregating the data using elasticsearch. But i am not able to pivot and aggregate the data in a single query as below:

Considering the data:

enter image description here

Is there a way to query the below result that pivots and aggregates the value as below:

enter image description here

Required Result:

{  
   {  
      "A":a1,
      "B":b1,
      "Value":3
   },
   {  
      "A":a1,
      "B":b2,
      "Value":3
   },
   {  
      "A":a2,
      "B":b2,
      "Value":4
   },
   {  
      "A":a1,
      "B":b3,
      "Value":11
   }
}

Solution

  • Yes, you can nest two terms aggregations for A and B, like this, and you'll get exactly the results you expect:

    {
      "size": 0,
      "aggs": {
        "A": {
          "terms": {
            "field": "A"
          },
          "aggs": {
            "B": {
              "terms": {
                "field": "B"
              },
              "aggs": {
                "value_sum": {
                  "sum": {
                    "field": "Value1"
                  }
                }
              }
            }
          }
        }
      }
    }