Choose nested when several conditions must apply to the same element in an array. Otherwise values from different elements can accidentally satisfy the query together.
A product with two variants
There is no red size L variant. But ordinary object mapping flattens these fields into multiple colors and multiple sizes, losing which size belongs to which color. A query for red and L can therefore match the product incorrectly.
Map variants as nested and color/size as keyword. Then use:
{
"query": {
"nested": {
"path": "variants",
"query": {
"bool": {
"filter": [
{"term":{"variants.color":"red"}},
{"term":{"variants.size":"L"}}
]
}
}
}
}
}
Both filters now run inside one nested element, so the example product does not match. Change L to S and it can match the red variant.
Nested elements create additional internal documents and more expensive queries. Ordinary object is simpler when preserving relationships inside arrays is unnecessary. Test both valid and cross-element combinations before deciding the mapping works.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate