Elasticsearch Nested Objects

Real data contains lists of small objects. A product holds many reviews, and each review has an author and a star rating. An order holds many line items, and each item has a name and a quantity. Elasticsearch stores such lists in a way that surprises beginners: it flattens them. The link between the fields of one object disappears, and searches return wrong matches.

The Flattening Problem

Consider a product with two reviews. Alice gave five stars. Bob gave two stars.

Original document:

  reviews: [
    { "author": "alice", "stars": 5 },
    { "author": "bob",   "stars": 2 }
  ]

How an ordinary object field stores it:

  reviews.author: [ "alice", "bob" ]
  reviews.stars:  [ 5, 2 ]

The pairing between author and stars is lost.

A search for "author is alice AND stars is 2" should return nothing, because Alice never gave two stars. The flattened version returns the product anyway. Alice appears in the author list, and the number 2 appears in the stars list.

The Nested Type Fixes the Problem

A nested field keeps each object as a separate hidden document. Elasticsearch stores the parent and its nested objects next to each other, and a special query searches inside one object at a time.

Ordinary object (flattened)         Nested type (kept apart)

  product                             product
    author: alice, bob                  ├── review { alice, 5 }
    stars:  5, 2                        └── review { bob,   2 }

Mapping a Nested Field

Declare the type as nested when creating the mapping. Existing fields cannot switch from object to nested, so plan the structure before indexing data.

PUT /products
{
  "mappings": {
    "properties": {
      "name": { "type": "text" },
      "reviews": {
        "type": "nested",
        "properties": {
          "author": { "type": "keyword" },
          "stars":  { "type": "integer" },
          "comment": { "type": "text" }
        }
      }
    }
  }
}

POST /products/_doc/1
{
  "name": "Trail Backpack",
  "reviews": [
    { "author": "alice", "stars": 5, "comment": "Sturdy and light" },
    { "author": "bob",   "stars": 2, "comment": "Zipper broke" }
  ]
}

Searching with a Nested Query

The nested query names the path of the nested field and holds an inner query. Every condition inside the inner query must match within the same nested object.

GET /products/_search
{
  "query": {
    "nested": {
      "path": "reviews",
      "query": {
        "bool": {
          "must": [
            { "term":  { "reviews.author": "alice" } },
            { "range": { "reviews.stars": { "gte": 4 } } }
          ]
        }
      }
    }
  }
}

The product matches because Alice gave five stars. The same query with stars equal to 2 returns nothing, which is the correct answer.

Seeing the Matching Objects with inner_hits

The search returns whole products by default. Add inner_hits to learn which nested objects matched.

"nested": {
  "path": "reviews",
  "query": { "term": { "reviews.author": "alice" } },
  "inner_hits": {}
}

The response lists each matching review under its product. A page can display the exact review that satisfied the search.

Aggregating Nested Data

Aggregations on nested fields need a nested aggregation that steps into the hidden documents first.

GET /products/_search
{
  "size": 0,
  "aggs": {
    "all_reviews": {
      "nested": { "path": "reviews" },
      "aggs": {
        "average_stars": { "avg": { "field": "reviews.stars" } }
      }
    }
  }
}

Choosing the Right Structure

StructureKeeps Object BoundariesBest For
objectNoSingle sub-objects such as an address
nestedYesLists where fields must match together
join (parent-child)Yes, with separate documentsChildren that change often on their own
flattenedNoObjects with unknown or huge field sets

Costs and Limits

Each nested object counts as a Lucene document. A product with 100 reviews creates 101 internal documents. Elasticsearch caps nested objects per document at 10,000 and nested fields per index at 50 by default. These limits protect memory and keep queries fast.

Updating one nested object rewrites the entire parent document and all of its nested objects. A review list that changes every second makes a poor nested field. Store frequently changing children as separate documents linked by a join field or an ID instead.

Update cost:

  Object with 3 reviews, 1 review edited  → rewrite 4 internal documents
  Object with 500 reviews, 1 edited       → rewrite 501 internal documents

Use nested fields when lists stay short and searches depend on the pairing of fields. Use plain objects everywhere else.

A Practical Example

An online course platform stores each course with a list of lessons. Every lesson has a title, a duration, and a difficulty level. Learners search for courses that contain a lesson titled "Indexes" with a duration under ten minutes. Both conditions must hold for the same lesson. A nested field answers the question correctly, while a flattened object would return courses that merely contain a short lesson and an unrelated lesson called "Indexes."

Test nested mappings with a few documents before loading real data. Search for combinations that should match and combinations that should fail. Both results confirm the structure behaves as intended.