Object and nested types help you store and search complex data with multiple layers inside Elasticsearch.
Object and nested types in Elasticsearch
PUT /my_index
{
"mappings": {
"properties": {
"user": {
"type": "object",
"properties": {
"name": { "type": "text" },
"age": { "type": "integer" }
}
},
"comments": {
"type": "nested",
"properties": {
"author": { "type": "text" },
"message": { "type": "text" }
}
}
}
}
}Object type stores data as a single JSON object inside a document.
Nested type stores arrays of objects separately to keep each object's fields linked during searches.
PUT /library
{
"mappings": {
"properties": {
"book": {
"type": "object",
"properties": {
"title": { "type": "text" },
"author": { "type": "text" }
}
}
}
}
}PUT /blog
{
"mappings": {
"properties": {
"comments": {
"type": "nested",
"properties": {
"user": { "type": "text" },
"comment": { "type": "text" }
}
}
}
}
}This program creates an index with object and nested types, adds a document, and searches for comments by author 'Bob'.
PUT /my_index
{
"mappings": {
"properties": {
"user": {
"type": "object",
"properties": {
"name": { "type": "text" },
"age": { "type": "integer" }
}
},
"comments": {
"type": "nested",
"properties": {
"author": { "type": "text" },
"message": { "type": "text" }
}
}
}
}
}
POST /my_index/_doc/1
{
"user": {
"name": "Alice",
"age": 30
},
"comments": [
{ "author": "Bob", "message": "Great post!" },
{ "author": "Carol", "message": "Thanks for sharing." }
]
}
GET /my_index/_search
{
"query": {
"nested": {
"path": "comments",
"query": {
"match": { "comments.author": "Bob" }
}
}
}
}Use object type for simple nested data without needing separate queries.
Use nested type when you want to search inside arrays of objects without mixing fields from different objects.
Remember to use nested queries when searching nested fields to get correct results.
Object type stores grouped fields as one JSON object inside a document.
Nested type stores arrays of objects separately to keep their fields linked during searches.
Use nested queries to search inside nested fields correctly.