How to Use Nested Aggregation in Elasticsearch
Use
nested aggregation in Elasticsearch to aggregate data inside nested fields by specifying the path to the nested object. Inside the nested aggregation, you can add sub-aggregations like terms or avg to analyze nested data separately from the main document.Syntax
The nested aggregation requires a path to the nested field. Inside it, you define sub-aggregations to analyze nested objects.
- nested: The aggregation type to access nested fields.
- path: The nested field's path in the document.
- aggs: Sub-aggregations to perform inside the nested context.
json
{
"aggs": {
"nested_agg_name": {
"nested": {
"path": "nested_field"
},
"aggs": {
"sub_agg_name": {
"terms": {
"field": "nested_field.sub_field.keyword"
}
}
}
}
}
}Example
This example shows how to aggregate the most common tags inside a nested tags field in documents.
json
{
"size": 0,
"aggs": {
"nested_tags": {
"nested": {
"path": "tags"
},
"aggs": {
"top_tags": {
"terms": {
"field": "tags.name.keyword",
"size": 3
}
}
}
}
}
}Output
{
"aggregations": {
"nested_tags": {
"doc_count": 5,
"top_tags": {
"buckets": [
{"key": "elasticsearch", "doc_count": 3},
{"key": "database", "doc_count": 2},
{"key": "search", "doc_count": 1}
]
}
}
}
}
Common Pitfalls
Common mistakes include:
- Not using the
nestedaggregation for nested fields, which returns incorrect results. - Using the wrong
paththat does not match the nested field's mapping. - Trying to aggregate nested fields without specifying
nested, causing aggregation on the root document instead.
Always check your mapping to confirm the nested field path.
json
{
"aggs": {
"wrong_agg": {
"terms": {
"field": "tags.name.keyword"
}
}
}
}
// Correct way:
{
"aggs": {
"nested_tags": {
"nested": {
"path": "tags"
},
"aggs": {
"top_tags": {
"terms": {
"field": "tags.name.keyword"
}
}
}
}
}
}Quick Reference
- nested aggregation: Use to access nested objects.
- path: Specify the nested field path.
- sub-aggregations: Define inside nested to analyze nested data.
- Check mapping: Confirm field is nested type.
Key Takeaways
Use
nested aggregation with the correct path to analyze nested fields.Always define sub-aggregations inside the
nested aggregation to get meaningful results.Check your index mapping to confirm the field is of nested type before using nested aggregation.
Avoid aggregating nested fields without
nested aggregation to prevent incorrect results.