0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Use Sub-Aggregation in Elasticsearch: Syntax and Examples

In Elasticsearch, you use sub-aggregation by nesting an aggregation inside another aggregation's aggs block. This lets you analyze data in layers, like grouping by one field and then further grouping or calculating metrics within those groups.
📐

Syntax

Sub-aggregation is defined inside the aggs section of a parent aggregation. The parent aggregation groups or filters data first, then the sub-aggregation runs on each group.

Key parts:

  • aggs: Container for aggregations.
  • Parent aggregation: Defines the first grouping or metric.
  • Sub-aggregation: Nested inside parent’s aggs, runs on each parent bucket.
json
{
  "aggs": {
    "parent_agg": {
      "terms": { "field": "field1" },
      "aggs": {
        "sub_agg": {
          "avg": { "field": "field2" }
        }
      }
    }
  }
}
💻

Example

This example groups documents by category and then calculates the average price within each category using a sub-aggregation.

json
{
  "size": 0,
  "aggs": {
    "categories": {
      "terms": { "field": "category.keyword" },
      "aggs": {
        "average_price": {
          "avg": { "field": "price" }
        }
      }
    }
  }
}
Output
{ "aggregations": { "categories": { "buckets": [ { "key": "books", "doc_count": 10, "average_price": { "value": 15.5 } }, { "key": "electronics", "doc_count": 5, "average_price": { "value": 120.0 } } ] } } }
⚠️

Common Pitfalls

Common mistakes when using sub-aggregations include:

  • Placing sub-aggregations outside the parent aggs block, which causes errors.
  • Using fields not suitable for aggregation (e.g., text fields without keyword).
  • Forgetting to set size: 0 if you only want aggregation results without hits.
json
{
  "aggs": {
    "wrong_sub_agg": {
      "avg": { "field": "price" }
    },
    "parent_agg": {
      "terms": { "field": "category.keyword" }
    }
  }
}

// Correct way:
{
  "aggs": {
    "parent_agg": {
      "terms": { "field": "category.keyword" },
      "aggs": {
        "sub_agg": {
          "avg": { "field": "price" }
        }
      }
    }
  }
}
📊

Quick Reference

ConceptDescription
Parent AggregationFirst level grouping or metric aggregation
Sub-AggregationNested aggregation inside parent to analyze each bucket further
aggsKeyword to define aggregations and sub-aggregations
size: 0Optional to hide document hits and show only aggregation results
Field TypesUse keyword or numeric fields for aggregations

Key Takeaways

Sub-aggregations are nested inside a parent aggregation's aggs block to analyze grouped data further.
Always place sub-aggregations inside the parent aggregation's aggs section to avoid errors.
Use keyword or numeric fields for aggregations; text fields need keyword subfields.
Set size to 0 if you want only aggregation results without document hits.
Sub-aggregations let you explore data in layers, like grouping then calculating metrics per group.