Object, Nested and Flattened
Each book now carries its reviews inside it: who wrote them and how many stars they gave. A manager asks for "books where Asha gave 5 stars" — and gets a book Asha rated 1 star. Nothing is broken; the reviews were mapped as plain objects. Choosing between object, nested and flattened is how you avoid that surprise.
The rule
Object merges array items, nested keeps them apart, flattened keeps them as plain values.
{
"title": "Rivers of Code",
"reviews": [
{ "user": "asha", "stars": 1 },
{ "user": "ben", "stars": 5 }
]
}Object (the default for any JSON object). Inner fields become dotted paths, and an array of objects is flattened into lists per field:
reviews.user → [ "asha", "ben" ]
reviews.stars → [ 1, 5 ]The link between "asha" and 1 is lost, so "user is asha AND stars is 5" matches this book. For a single object, like "publisher": {"name": ..., "city": ...}, that loss does not matter, and object is the right choice.
Nested keeps each array item as its own hidden document, so fields stay paired:
"reviews": {
"type": "nested",
"properties": { "user": { "type": "keyword" }, "stars": { "type": "integer" } }
}You must then query it with a nested query that checks conditions inside one item at a time:
GET /books/_search
{
"query": {
"nested": {
"path": "reviews",
"query": { "bool": { "must": [
{ "term": { "reviews.user": "asha" } },
{ "term": { "reviews.stars": 5 } }
] } }
}
}
}Now Rivers of Code is correctly not returned. The cost: every nested item is an extra hidden document, so heavy use makes indexing and queries slower.
Flattened maps an entire object as one field. Every leaf value is indexed as a keyword, and no new sub-fields are added to the mapping, however many keys arrive. It suits unpredictable key-value data such as "attributes": {"binding": "hardback", "signed": "yes"} and cures mapping explosions. In exchange, values are treated as keywords only — no full-text analysis, and numbers compare as text.
The shortcut
Ask two questions: "is it an array of objects whose fields must stay paired?" → nested. Otherwise "are the keys unpredictable?" → flattened. Otherwise → object.
publisher
One object, fixed keys →
object.
Drills
Answer fast — trust the rule.
With reviews as a plain object array, why does "user asha AND stars 5" match a book where asha gave 1 star?
What must you use to search a nested field?
Sellers add arbitrary keys like signed, edition and cover_art_by. Which type keeps the mapping from growing?
What is the main cost of nested?
Remember
- Object merges array items, nested keeps them apart, flattened keeps them as plain values.
- Paired fields in an array → nested; unpredictable keys → flattened; otherwise object.
- Nested needs a
nestedquery; flattened values are keywords only.
