How to Use a Nested Query
To run a nested query, you must have an index that includes a nested mapping.
The following query creates an index with a nested field mapping.
{
"mappings": {
"properties": {
"customers": {
"type": "nested"
}
}
}
}
Next, create a document containing nested field types and some data as shown in the sample query below:
{
"category": "electronic_purchases",
"customers": [
{
"first_name": "Barbra",
"last_name": "Walker"
},
{
"first_name": "Michael",
"last_name": "Jean"
},
{
"first_name": "Hannah",
"last_name": "Newsome"
}
]
}
To run a nested query, we can execute an example such as the one shown below:
{
"query": {
"nested": {
"path": "customers",
"query": {
"bool": {
"must": [
{"match": {
"customers.first_name": "Hannah"
}
}
]
}
},
"inner_hits": {"highlight": {"fields": {"customers.first_name": {}}}}
}
}
}
An example response from the above query is below:
The nested query uses parameters as:
- Path – The path parameter defines the path to the nested object under which to perform the search query. This parameter is required.
- Query – This parameter defines the search query to execute on the provided nested path. Similar to the path parameter, the query parameter is non-optional.
- Bool – The Boolean query ensures that the documents match the specified condition. When you have the Boolean query set to must, the set clause must be in the matching record. Consider the documentation on the Boolean query to learn more.
- Inner_hits – this returns per search hit in the response of the nested response. It accepts options such as highlight followed by the field to highlight.
Multi-Level Nested Queries
You can also have multi-level nested queries as shown in the example index:
{
"mappings": {
"properties": {
"username": {
"type": "nested",
"properties": {
"first_name": {
"type": "text"
},
"email": {
"type": "nested",
"properties": {
"provider": {
"type": "text"
},
"prefix": {
"type": "text"
}
}
}
}
}
}
}
}
Add a few documents with the data as:
{
"username":{
"first_name": "David",
"email": [
{
"provider": "gmail.com",
"prefix": "david123@"
},
{
"provider": "hotmail.com",
"prefix": "davidy123@"
}
]
}
}
PUT /users/_doc/2
{
"username":{
"first_name": "Lucy",
"email": [
{
"provider": "outlook.com",
"prefix": "lucymail@"
},
{
"provider": "protonmail.com",
"prefix": "lucyp@"
}
]
}
}
To perform a multi-level nested query, execute the request as:
{
"query": {
"nested": {
"path": "username",
"query": {
"nested": {
"path": "username.email",
"query": {
"bool": {
"must": [
{"match": {
"username.email.provider": "gmail.com"
}}
]
}
}
}
}
}
}
}
An example of the response from the resulting query is below:
In closing
This guide discusses how to run nested and multi-level nested queries in Elasticsearch.