Problem:
Create arrays of objects within an index and query them independently of each other.
Default object mapping won't work as you can see here.
Solution Summary:
The "nested" type, a specialised version of the object datatype, allows arrays of objects to be indexed and queried independently of each other. Internally, nested objects index each object in the array as a separate hidden document, meaning that each nested object can be queried independently of the others, with the nested query:
Prerequisites:
Working Elasticsearch setup with Kibana.
Data is created based on the accounts data we were working on from here, but you can follow this lab independently as we are setting up data again.
If you are following along from, you will have to delete the index you already created for department:
DELETE department
Solution Steps:
Data Setup
I will create arrays of employees in two departments, based on the accounts data we were working on from here.
First I will create a mapping to make the type of employees as "nested":
PUT department
{
"mappings": {
"_doc": {
"properties": {
"employees": {
"type": "nested"
}
}
}
}
}
We will add two documents with nested array of objects:
POST /department/_doc/1
{
"name":"accounts",
"employees": [
{
"firstname": "Garrett",
"lastname": "Langley",
"age": 36,
"gender": "M",
"address": "331 Bowne Street"
},
{
"firstname": "Mallory",
"lastname": "Emerson",
"age": 24,
"gender": "F",
"address": "318 Dunne Court"
}
]
}
POST /department/_doc/2
{
"name":"hr",
"employees": [
{
"firstname": "Lavonne",
"lastname": "Reyes",
"age": 31,
"gender": "F",
"address": "983 Newport Street"
},
{
"firstname": "Lidia",
"lastname": "Guerrero",
"age": 30,
"gender": "M",
"address": "254 Stratford Road"
}
]
}
Nested Query
We will embed othe same bool query from previous recipe as a "nested" query specifying the "path" to the nested array.
GET department/_doc/_search
{
"query": {
"nested": {
"path": "employees",
"query": {
"bool": {
"must": [
{ "term": { "employees.age": 30 }},
{ "term": { "employees.gender.keyword": "F" }}
]
}
}
}
}
}
Note: This time it will return only the correct department (accounts).
Recent comments