Agregaciones anidadas y subagregaciones
Aprenda a combinar agregaciones anidando métricas dentro de buckets, crear análisis multinivel y recorrer estructuras de documentos anidadas con la agregación nested.
Agregaciones anidadas y subagregaciones es una lección gratuita de Elasticsearch & Full Text Search Systems en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Elasticsearch & Full Text Search Systems, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Elasticsearch & Full Text Search Systems incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Combining Aggregations
A single aggregation answers one question. Real analytics often need layered answers: average price per category, or top brands per region. Elasticsearch lets you nest aggregations inside one another.
This lesson shows how to compose them.
The aggs Hierarchy
Any bucket aggregation can contain a sub-aggs block. The sub-aggregation runs once per bucket, operating only on the documents in that bucket.
This is the core mechanism for multi-dimensional analytics.
Metric Inside a Bucket
Here we group documents by category, then compute the average price within each group. The metric aggregation lives inside the bucket aggregation's aggs.
GET sales/_search
{
"size": 0,
"aggs": {
"by_category": {
"terms": { "field": "category" },
"aggs": {
"avg_price": { "avg": { "field": "price" } }
}
}
}
}Reading the Result
Each bucket in by_category now carries an avg_price value alongside its doc_count. You get the category name, how many docs it holds, and its average price in one response.
Bucket Inside a Bucket
You can nest bucket aggregations too. Group by region, then by brand within each region. This produces a two-level breakdown.
"aggs": {
"by_region": {
"terms": { "field": "region" },
"aggs": {
"by_brand": { "terms": { "field": "brand" } }
}
}
}Mind the Cardinality
Deeply nested terms aggregations can explode combinatorially. A region with 50 brands across 20 regions yields up to 1,000 buckets. Use the size parameter to limit returned buckets and protect memory.
Multiple Sub-Aggregations
A bucket can hold several sub-aggregations at once. Here each category reports both its average and maximum price.
"by_category": {
"terms": { "field": "category" },
"aggs": {
"avg_price": { "avg": { "field": "price" } },
"max_price": { "max": { "field": "price" } }
}
}The nested Aggregation
When data uses the nested field type, you must enter that scope with a nested aggregation before aggregating on its inner fields. It points at a path.
"aggs": {
"variants": {
"nested": { "path": "variants" },
"aggs": {
"avg_qty": { "avg": { "field": "variants.quantity" } }
}
}
}Reverse Nested
Inside a nested aggregation you can jump back to the parent document scope using reverse_nested. This lets you count distinct parent docs that contain a matching nested element.
"reverse_nested": {},
"aggs": {
"parent_count": { "value_count": { "field": "_id" } }
}Sorting Buckets by a Metric
Order parent buckets by a nested sub-metric using order. Here categories are sorted by their average price, descending.
"terms": {
"field": "category",
"order": { "avg_price": "desc" }
}Design Tips
Keep nesting shallow when possible, always set size on inner terms, and put the most selective bucket aggregation first to reduce the work done by deeper levels.
Quick Check
Test your grasp of sub-aggregations.
Recap
You learned to compose aggregations:
- Any bucket aggregation can hold sub-
aggsthat run per bucket. - Nest metrics in buckets, or buckets in buckets for multi-level breakdowns.
- Use the
nestedandreverse_nestedaggregations to traverse nested document scopes. - Control bucket explosion with
sizeand order buckets by sub-metrics withorder.
Preguntas frecuentes
¿La lección «Agregaciones anidadas y subagregaciones» es gratis?
Sí — el texto completo de «Agregaciones anidadas y subagregaciones» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Elasticsearch & Full Text Search Systems, actualiza a CoddyKit PRO. El curso de Elasticsearch & Full Text Search Systems incluye 4 lecciones en total.
¿Qué aprenderé en «Agregaciones anidadas y subagregaciones»?
Aprenda a combinar agregaciones anidando métricas dentro de buckets, crear análisis multinivel y recorrer estructuras de documentos anidadas con la agregación nested. Practicas Elasticsearch & Full Text Search Systems con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Elasticsearch & Full Text Search Systems?
No se requiere experiencia previa. Elasticsearch & Full Text Search Systems en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Agregaciones anidadas y subagregaciones»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Elasticsearch & Full Text Search Systems?
Sí. Cada lección de Elasticsearch & Full Text Search Systems incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Agregaciones de métricas
- Agregaciones de buckets
- Agregaciones de pipeline
- Agregaciones anidadas y subagregaciones