Skip to the workspace
Pebellslearn by building
Data Types  ›  Capstone Project

Object, Nested and Flattened

Nested 15 minObject fields merge array items into per-field lists, nested fields keep each item separate at extra cost, and flattened fields store a whole object as keyword values.

elasticsearch / Object, Nested and Flattened

Explore each scene at your own pace.

01 · The rule

The rule

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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.