Nested queries help you search inside objects that are stored within other objects. This lets you find data deep inside complex records.
0
0
Nested queries for nested objects in Elasticsearch
Introduction
You have a list of items inside a record and want to find records with specific items.
You want to search for a person who has a job with a certain title inside their job history.
You need to filter products that have reviews with a certain rating.
You want to find orders that contain products with a specific feature.
Syntax
Elasticsearch
{
"query": {
"nested": {
"path": "path_to_nested_object",
"query": {
"match": {
"path_to_nested_object.field": "value"
}
}
}
}
}The path tells Elasticsearch where the nested object is inside the main document.
The query inside nested works like a normal query but only inside the nested objects.
Examples
Searches for documents where any comment's message contains the word "great".
Elasticsearch
{
"query": {
"nested": {
"path": "comments",
"query": {
"match": {
"comments.message": "great"
}
}
}
}
}Finds documents where an author named "Alice" is at least 30 years old.
Elasticsearch
{
"query": {
"nested": {
"path": "authors",
"query": {
"bool": {
"must": [
{ "match": { "authors.name": "Alice" } },
{ "range": { "authors.age": { "gte": 30 } } }
]
}
}
}
}
}Sample Program
This query finds documents where there is at least one product named "laptop" with a price less than or equal to 1000.
Elasticsearch
{
"query": {
"nested": {
"path": "products",
"query": {
"bool": {
"must": [
{ "match": { "products.name": "laptop" } },
{ "range": { "products.price": { "lte": 1000 } } }
]
}
}
}
}
}OutputSuccess
Important Notes
Nested queries only work if the field is mapped as nested in Elasticsearch.
Without the nested mapping, Elasticsearch treats objects as flat and nested queries won't work correctly.
You can combine nested queries with other queries using bool to build complex searches.
Summary
Nested queries let you search inside objects stored within other objects.
Use the path to point to the nested object location.
Nested queries require the field to be mapped as nested in Elasticsearch.