0
0
Elasticsearchquery~5 mins

Nested aggregations in Elasticsearch

Choose your learning style9 modes available
Introduction

Nested aggregations help you group and analyze data inside other groups. This lets you explore details step by step, like looking inside boxes within boxes.

You want to find the average price of products grouped by category and then by brand.
You need to count how many users visited each country and then each city inside that country.
You want to see sales totals by year and then by month within each year.
You want to analyze customer reviews by product and then by rating score.
Syntax
Elasticsearch
{
  "aggs": {
    "group1": {
      "terms": { "field": "field1.keyword" },
      "aggs": {
        "group2": {
          "terms": { "field": "field2.keyword" }
        }
      }
    }
  }
}

Each aggregation can contain another aggregation inside the aggs key.

The inner aggregation works on the results of the outer aggregation.

Examples
This groups products first by category, then inside each category by brand.
Elasticsearch
{
  "aggs": {
    "by_category": {
      "terms": { "field": "category.keyword" },
      "aggs": {
        "by_brand": {
          "terms": { "field": "brand.keyword" }
        }
      }
    }
  }
}
This groups data by year, then inside each year by month using date histograms.
Elasticsearch
{
  "aggs": {
    "by_year": {
      "date_histogram": {
        "field": "date",
        "calendar_interval": "year"
      },
      "aggs": {
        "by_month": {
          "date_histogram": {
            "field": "date",
            "calendar_interval": "month"
          }
        }
      }
    }
  }
}
Sample Program

This query counts documents grouped by country, then inside each country by city.

Elasticsearch
{
  "size": 0,
  "aggs": {
    "by_country": {
      "terms": { "field": "country.keyword" },
      "aggs": {
        "by_city": {
          "terms": { "field": "city.keyword" }
        }
      }
    }
  }
}
OutputSuccess
Important Notes

Nested aggregations let you explore data step by step, like peeling layers of an onion.

Make sure the fields you use for grouping are keyword or not analyzed fields for exact matches.

Summary

Nested aggregations group data inside other groups.

Use the aggs key inside an aggregation to add a nested aggregation.

This helps analyze data in multiple levels, like country then city.