Getting sum sub aggregation

I'd like to get the sum of a sub aggregation. For example, I have group by smartphones, group by carrier and then the average price for that carrier. I'd like to get the sum of all prices for all carriers for a specific smartphone. So essentially, I want something like this:

{
  "aggs": {
    "group_by_smartphones": {
      "terms": {
        "field": "smartphone",
        "order": {
          "_term": "asc"
        },
        "size": 200
      },
      "aggs": {
        "group_by_sum": {
          "sum": {
            "field": "price"
          },
          "aggs": {
            "group_by_carrier": {
              "terms": {
                "field": "carrier",
                "order": {
                  "group_by_avg": "desc"
                }
              },
              "aggs": {
                "group_by_avg": {
                  "avg": {
                    "field": "price"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Except, when I do it like this I get this error:

"type": "aggregation_initialization_exception", "reason": "Aggregator [group_by_sum] of type [sum] cannot accept sub-aggregations"

How do I fix it so I can get the sum of all prices for each smartphone?

Try the following. The problem with your request was that you were trying to do a sub aggregation under the sum aggregation which is not allowed. Metric aggregations like sum provide just a scalar output so cannot support sub-aggregations like bucket aggregations (which provide a bucket of documents) can.

You can, however have multiple aggregations at each level so what the below request is doing is asking for a terms aggregation by smartphone and then for each smartphone bucket created it is passing the documents in that bucket to both the sum aggregation (to get the sum of the price over all documents for that smartphone) and to the group_by_carrier terms aggregation (to get the average price of each carrier).

Hope that helps

{
  "aggs": {
    "group_by_smartphones": {
      "terms": {
        "field": "smartphone",
        "order": {
          "_term": "asc"
        },
        "size": 200
      },
      "aggs": {
        "group_by_sum": {
          "sum": {
            "field": "price"
          },
          "group_by_carrier": {
            "terms": {
              "field": "carrier",
              "order": {
                "group_by_avg": "desc"
              }
            },
            "aggs": {
              "group_by_avg": {
                "avg": {
                  "field": "price"
                }
              }
            }
          }
        }
      }
    }
  }
}
1 Like

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