Tipos de campos anidados y de objeto
Aprenda cómo Elasticsearch gestiona los objetos y arrays JSON, por qué el tipo de objeto predeterminado aplana los datos y cómo el tipo nested conserva las relaciones dentro de arrays de objetos.
Tipos de campos anidados y de objeto 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.
Storing Structured Data
Real-world documents often contain nested structures: a blog post with comments, a product with variants, or an order with line items. Elasticsearch must decide how to index these JSON objects so they stay searchable.
This lesson covers the two main approaches: the default object type and the specialized nested type.
The Default object Type
By default, any JSON object inside a document is mapped as the object type. Elasticsearch flattens the inner fields into dotted paths.
A field author.name simply becomes a normal Lucene field. This is efficient and works perfectly for single objects.
PUT my_index/_doc/1
{
"author": { "first": "Jane", "last": "Doe" }
}How Flattening Looks
Internally the object above is stored as two flat fields: author.first = Jane and author.last = Doe. The hierarchy is only conceptual; Lucene sees independent fields.
This is fine until you have an array of objects.
The Flattening Problem
Consider an array of users. After flattening, Elasticsearch loses the link between which first name belongs to which last name.
The arrays become user.first = [Alice, John] and user.last = [White, Smith] separately.
PUT my_index/_doc/2
{
"user": [
{ "first": "Alice", "last": "White" },
{ "first": "John", "last": "Smith" }
]
}Why It Matters
A query for first = Alice AND last = Smith would incorrectly match the document above, because the cross-object relationship is gone. The values are pooled together.
The nested type solves this.
Declaring a Nested Field
Set the field type to nested in the mapping. Each object in the array is then indexed as a hidden, separate Lucene document, preserving its internal field relationships.
PUT my_index
{
"mappings": {
"properties": {
"user": { "type": "nested" }
}
}
}Querying Nested Fields
You must use a nested query and specify the path. Conditions inside are evaluated against a single sub-document, so cross-object false matches disappear.
GET my_index/_search
{
"query": {
"nested": {
"path": "user",
"query": {
"bool": { "must": [
{ "match": { "user.first": "Alice" }},
{ "match": { "user.last": "Smith" }}
]}
}
}
}
}Inner Hits
Add inner_hits to a nested query to return which specific sub-document(s) matched, not just the parent document. This is essential for highlighting the relevant array element.
"nested": {
"path": "user",
"inner_hits": {},
"query": { "match": { "user.first": "Alice" } }
}Costs of Nested
Nested fields are powerful but have trade-offs:
- Each array element is a separate Lucene doc, increasing index size.
- Updating one element re-indexes the whole parent document.
- Deeply nested or large arrays can hurt performance.
Use the index.mapping.nested_objects.limit setting to cap counts.
Nested vs join
For tightly coupled data that updates together, nested is ideal. For independently updated, high-cardinality relationships, consider the join (parent-child) field type instead, which decouples updates at a higher query cost.
When to Choose Which
Use object when arrays do not require cross-field correlation. Use nested when you must match multiple fields within the same array element. Defaulting to nested for everything wastes resources.
Quick Check
Test your understanding of nested mappings.
Recap
You learned how Elasticsearch indexes JSON objects:
- The default
objecttype flattens fields and pools array values. - The
nestedtype indexes each array element separately to preserve relationships. - Query nested fields with the
nestedquery plus apath, and useinner_hitsto find matching elements. - Nested types cost more storage and require full re-indexing on element updates.
Aprende Elasticsearch & Full Text Search Systems con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 12
- Lecciones
- 48
Preguntas frecuentes
¿La lección «Tipos de campos anidados y de objeto» es gratis?
Sí — el texto completo de «Tipos de campos anidados y de objeto» 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 «Tipos de campos anidados y de objeto»?
Aprenda cómo Elasticsearch gestiona los objetos y arrays JSON, por qué el tipo de objeto predeterminado aplana los datos y cómo el tipo nested conserva las relaciones dentro de arrays de objetos. 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 «Tipos de campos anidados y de objeto»?
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
- Personalización de mappings de campos
- Mappings dinámicos frente a explícitos
- Plantillas y alias de índices
- Tipos de campos anidados y de objeto