The Nested Data Type in Elasticsearch
How Elasticsearch quietly solves one of the trickiest problems in search engines: keeping arrays of related objects from lying to your queries.
Imagine a filing cabinet where every folder gets shredded and its pages get mixed into one giant pile before being put away. That is roughly what happens to arrays of objects inside a normal Elasticsearch document. The nested data type exists to stop that shredding from happening — to keep each folder’s pages together, sealed, and searchable as a unit. In this guide we will build up, piece by piece, exactly why that shredding happens, what problems it causes, and how the nested type quietly fixes it under the hood.
1What Elasticsearch Actually Stores
Before we can understand the nested type, we need to understand the shape of the thing it is trying to fix.
Documents, Fields, and the Illusion of Structure
Elasticsearch stores data as JSON documents. Each document is made of fields, and fields can hold plain values like text and numbers, or they can hold objects — JSON structures nested inside other JSON structures. On the surface, an Elasticsearch document looks exactly like the JSON you would send to any modern web API: friendly, hierarchical, and human-readable.
Underneath that friendly JSON, however, Elasticsearch is built on Apache Lucene, a search library that has no concept of nested JSON at all. Lucene only understands a flat structure: a document is a bag of field-name-to-value pairs, all sitting at the same level. Every time Elasticsearch accepts a rich, hierarchical JSON document, it has to translate that hierarchy into something Lucene’s flat model can store.
Think of Lucene as a librarian who only accepts index cards — one flat card per book, no folders, no binders. If you hand her a filing folder full of related pages, she does not reject it; she simply staples every page’s important words onto the same card. The folder’s boundaries disappear, but the words are still searchable.
For simple objects — a single nested JSON object with no siblings — this translation is harmless. Elasticsearch flattens the object’s fields using dot notation internally (for example address.city and address.zip) and everything still works because there is only one “version” of that object per document.
The trouble starts the moment that object stops being singular and becomes an array — a list of similar objects living inside the same document. That is exactly the scenario this entire guide exists to explain.
It is worth being precise about why a single object causes no trouble at all: with only one instance of address, there is only one value for city and one value for zip per document, so there is nothing to accidentally cross-match. The moment a second, third, or hundredth instance of a similarly-shaped object appears in the same array, every additional entry introduces another opportunity for its fields to be flattened alongside — and potentially confused with — the fields of every other entry in that same array.
Whenever a field in your schema is an array of JSON objects — not an array of plain strings or numbers, but an array where each entry itself has multiple named properties — that field deserves a deliberate decision about object versus nested mapping, rather than being left at the default.
Document
A single JSON record stored and retrieved as one unit in Elasticsearch, similar to a row in a table.
Field
A named piece of data inside a document, such as title, price, or comments.
Mapping
The schema that tells Elasticsearch what type each field is — text, number, object, or nested.
Lucene
The underlying search library Elasticsearch is built on; it only understands flat, non-hierarchical documents.
2The Problem: When Arrays of Objects Go Wrong
This is the single most important chapter in the entire guide — everything else exists to fix the problem described here.
Suppose you are indexing a product document, and the product has a list of reviews. Each review has an author name and a rating. If you map that reviews field as a plain object type (the default), Elasticsearch will flatten every review’s author values into one array of authors, and every review’s rating values into a completely separate array of ratings. The pairing between a specific author and their specific rating is lost — the two arrays sit side by side, but nothing tells Elasticsearch that the third author belongs with the third rating.
If reviewer “Alice” gave a rating of 1, and reviewer “Bob” gave a rating of 5, a flattened object field can no longer tell the difference between “Alice rated it 1” and “Alice rated it 5.” A search for “reviews where Alice gave 1 star” can wrongly match a document where Alice gave 5 stars and someone else gave 1 star.
Picture two egg cartons — one full of names, one full of numbers — poured into the same bowl. You can still tell which names and which numbers are in the bowl, but you can no longer tell which name was originally paired with which number. That bowl is what a flattened array of objects looks like to Elasticsearch.
This is not a rare edge case. It happens with any array of objects: order line items, employee skill ratings, product variants with prices, comments with authors and timestamps, event logs with users and actions. Anywhere a document contains “a list of things, and each thing has more than one property,” this cross-object matching problem is lurking.
| Scenario | What Goes Wrong With a Plain Object Field |
|---|---|
| Product reviews (author + rating) | A search for one author’s specific rating can match a different author’s rating instead |
| Order line items (product + quantity) | Searching for “5 units of Product A” can match a document where Product A appears with a different quantity |
| Employee skills (skill + level) | Filtering for “Expert in Java” can match an employee who is only a Beginner in Java but Expert in something else |
| Event logs (user + action) | Searching for “User X performed Delete” can match a log where User X performed a harmless action and someone else deleted |
This is precisely the gap the nested data type was built to close. It does not change how you write your JSON; it changes how Elasticsearch stores and queries that JSON internally, so that each object in the array keeps its own identity instead of being poured into the same bowl as its siblings.
It is worth pausing on why this problem is so easy to miss during development but so damaging in production. Early testing usually happens with small, hand-crafted sample documents — often just one or two entries per array — where the flattening behavior of a plain object field happens to produce correct-looking results purely by coincidence, since there is little for the values to get mixed up with. The mismatch only becomes visible once real, messier data arrives: hundreds of reviews per product, dozens of line items per order, or many skills per candidate, at which point queries that once looked correct begin quietly returning wrong documents, often without any error, warning, or obvious symptom pointing back to the mapping choice.
Because the flattened object field still returns results — just occasionally the wrong ones — this class of bug rarely triggers exceptions, alerts, or crash reports. It surfaces instead as slow-building user complaints about “search returning irrelevant results,” which are far harder to trace back to a mapping decision made months earlier.
3Core Concept: What the Nested Type Actually Does
Once you understand the problem, the solution is surprisingly elegant.
The nested data type is a special version of the object data type. Instead of flattening every object in an array into one shared bag of fields, Elasticsearch takes each object in the array and stores it as its own hidden, separate Lucene document, sitting alongside the main document. The relationship between the fields inside one object — author and rating, for example — stays intact because they physically live in the same tiny hidden document, not smeared across a shared array.
The Core Idea in One Sentence
A nested field turns “one document with an array of objects” into “one parent document plus several small, invisible child documents, one per array entry, that Elasticsearch keeps glued together internally.”
Because each nested object becomes its own independent Lucene document, queries against nested fields can ask precise questions like “find a document where at least one review has author Alice AND rating 1” — and get the correct answer, because the author and rating fields being tested are guaranteed to come from the exact same hidden document, not different ones.
Instead of pouring the egg cartons into one bowl, nested storage keeps each egg in its own small labeled cup, and all the cups are kept in the same tray. You can now search “find the tray that has a cup labeled Alice with the number 1 inside it” and get a truthful answer, because each cup keeps its own contents separate.
Nested is a mapping-time decision, not a query-time trick. You must explicitly declare a field as "type": "nested" in the mapping before indexing data — Elasticsearch will not automatically detect that an array of objects needs nested treatment.
Object Type
Flattens all objects in an array into shared, cross-linked field arrays. Fast and simple, but loses object boundaries.
Nested Type
Stores each array entry as its own hidden Lucene document, preserving exact field relationships within each entry.
Storage Cost
Every nested object becomes an additional physical Lucene document, which increases total document count and index size.
Query Cost
Nested queries must “join” parent and child documents internally at query time, which is more expensive than a plain field lookup.
4Architecture: How Nested Documents Live Inside an Index
Understanding the physical layout inside the index makes every later chapter about queries and performance click into place.
An Elasticsearch index is really a collection of Lucene segments, and each segment stores a flat sequence of documents. When you index a document containing a nested field with three array entries, Elasticsearch does not store one Lucene document — it stores four: the three nested child documents, plus one parent document holding all the “regular” (non-nested) fields.
Elasticsearch keeps these documents adjacent to each other inside the Lucene segment, in a specific order, and uses an internal marker so it always knows which child documents belong to which parent. This physical adjacency is what allows Elasticsearch to reconstruct the parent-child relationship quickly at query time without needing a separate index or a database-style join.
graph TD
A[Parent Document: Product] --> B[Hidden Child Doc 1: Review by Alice, rating 1]
A --> C[Hidden Child Doc 2: Review by Bob, rating 5]
A --> D[Hidden Child Doc 3: Review by Carol, rating 4]
B -.stored adjacently.-> A
C -.stored adjacently.-> A
D -.stored adjacently.-> A
This adjacency has a strict rule attached to it: nested child documents and their parent must always live in the same Lucene segment, and Elasticsearch enforces this by blocking certain operations — like updating a document’s nested field in isolation — that would otherwise break the physical grouping. Whenever a document with nested fields is updated, Elasticsearch must reindex the entire parent document along with all of its nested children as one atomic unit.
You cannot update just one nested object inside an array without Elasticsearch rewriting the whole parent document and all of its nested children together. There is no concept of editing “just the third review” in isolation at the storage layer.
Every hidden nested document also inherits a special internal field that records its nesting “path” — essentially, which nested field and which parent it belongs to. This is how a query can ask specifically about the reviews nested path and ignore hidden documents belonging to some other nested field, such as images, on the same parent.
Segment merging — the background process where Lucene periodically combines smaller segments into larger ones to keep search efficient — has to respect this adjacency rule as well. When Elasticsearch merges segments, it carefully carries each parent’s block of hidden child documents along with it as one unit, rather than treating documents individually, ensuring that the physical grouping guarantee holds even as segments are rewritten and consolidated over the life of an index.
Deleting a document with nested fields marks the entire block — parent plus all hidden children — for removal together during the next merge, rather than deleting individual pieces, which keeps the adjacency invariant intact even under deletion.
It helps to compare this layout against a completely different approach: the Elasticsearch join data type, which also models parent-child relationships but does so using entirely separate top-level documents connected only by a shared join field, rather than hidden documents glued to a specific parent. A join relationship allows child documents to be indexed, updated, and deleted independently of their parent, at the cost of needing an explicit join field in every document and generally slower queries, since matching parents to children happens across the whole shard rather than within a tightly adjacent block.
| Aspect | Nested Type | Join Type |
|---|---|---|
| Physical Storage | Hidden documents adjacent to parent in the same segment | Fully separate top-level documents linked by a join field |
| Update Independence | No — updating any nested entry rewrites the whole parent | Yes — children can be updated without touching the parent |
| Query Speed | Fast, since children are physically adjacent to their parent | Slower, since matching spans the whole shard |
| Best Fit | Small, bounded arrays queried together with their parent | Large, frequently-changing, independently-queried relationships |
5Internal Working: What Happens When You Index a Document
Let’s trace one document from JSON to disk, step by step.
The moment Elasticsearch receives a JSON document that contains a nested field, its indexing pipeline treats that array specially, using the mapping to recognize the field as nested rather than a plain object. The pipeline then breaks the incoming document apart into multiple smaller documents before anything is written to disk.
Mapping Lookup
Elasticsearch checks the index mapping and sees that the incoming field, for example reviews, is declared as type: nested rather than the default object type.
Splitting the Array
Each entry in the array is pulled out and treated as its own self-contained document, keeping its internal fields exactly as given, without merging them into any shared array.
Tagging With Nested Path Metadata
Each hidden child document is tagged internally with the path of the nested field it came from, so Elasticsearch can later distinguish reviews from, say, images or line-items on the same parent.
Ordering for Adjacency
The child documents are placed directly before the parent document in the same block, in a fixed, predictable block order that the query engine relies on later.
Segment Write
The whole block — all child documents plus the parent — is written together into the same Lucene segment during the next refresh, guaranteeing they are never split apart.
sequenceDiagram
participant Client
participant ES as Elasticsearch Indexing Pipeline
participant Lucene as Lucene Segment
Client->>ES: Send document with nested "reviews" array
ES->>ES: Check mapping - reviews is nested
ES->>ES: Split array into hidden child documents
ES->>ES: Tag each child with nested path
ES->>Lucene: Write children + parent together, adjacent
Lucene-->>ES: Acknowledge write
ES-->>Client: Index response
This block-adjacency trick is also what makes queries fast later on: because the child documents always sit right before their parent, Elasticsearch’s query engine can scan forward from a matching child and immediately know which parent it belongs to, without needing to look anything up in a separate table or perform a database-style join across unrelated storage locations.
6Data Flow: How a Nested Query Finds Its Answer
Indexing is only half the story — searching is where the real payoff of nested storage becomes visible.
A nested query never searches the fields inside a nested object directly at the top level. Instead, it wraps the condition in a special query type that tells Elasticsearch, “search only among the hidden child documents belonging to this nested path, and if any single child document matches every condition inside this query, count the parent as a match.”
It’s like telling a librarian, “search inside each individual folder for a page that mentions both ‘Alice’ and ‘1 star’ on the very same page — don’t count it if ‘Alice’ is on one page and ‘1 star’ is on a completely different page in the same folder.” The nested query enforces exactly that same-page requirement.
flowchart LR
Q[Nested Query on 'reviews'] --> S{Scan hidden child documents}
S -->|Child matches ALL inner conditions| M[Mark parent as candidate]
S -->|Child matches only SOME conditions| X[Ignore - not a full match]
M --> R[Return parent document in results]
Because scoring and matching happen at the level of the individual hidden child document, Elasticsearch can also return “which specific nested object matched” using a feature called inner hits, letting an application show not just “this product matched” but “this specific review, by this specific author, is the one that matched.”
Inner hits let a nested query return the exact matching child object alongside the parent, so applications can highlight “which review” or “which line item” caused the document to appear in the results, instead of just returning the whole parent and leaving the application guessing.
Nested aggregations follow the same philosophy. A nested aggregation first narrows the aggregation scope down to only the hidden child documents under a given nested path, computes statistics — averages, counts, min and max — purely among those children, and then optionally reverses back up to the parent level using a “reverse nested” aggregation when you need to combine nested-level insights with parent-level fields.
Consider a concrete example: computing the average rating across all reviews, broken down by which country the parent product ships from. The average itself must be computed at the nested review level, since ratings live inside review objects, but the “ships from” grouping lives on the parent product. A reverse nested aggregation bridges this gap by stepping back out of the nested review scope to reach the parent’s country field, letting the two levels of the hierarchy combine into a single, accurate report — something that would be far more awkward to express correctly against a flattened object field.
Performance-wise, nested queries and aggregations are generally efficient precisely because of the physical adjacency described earlier: Elasticsearch does not need to perform a costly cross-index lookup to connect a matching child back to its parent, since the two are guaranteed to sit within a short, predictable distance of each other in the same segment. This is a meaningfully different performance profile from the join data type, where parent and child live in entirely separate documents and matching them requires broader, more expensive lookups.
| Operation | What It Does |
|---|---|
| Nested Query | Finds parent documents where at least one nested child satisfies all inner conditions together |
| Inner Hits | Returns the exact matching nested child object(s), not just the parent |
| Nested Aggregation | Computes statistics scoped only to the hidden child documents of a nested path |
| Reverse Nested Aggregation | Steps back up from nested-child scope to parent-document scope inside an aggregation |
7Working With Nested Fields: Common Query Shapes
A tour of the query patterns you will reach for again and again once a field is mapped as nested.
The most fundamental pattern is the single-condition nested query, which simply asks whether at least one hidden child document under a given path has a field matching a given value — for example, “at least one review has a rating of 5.” Even with only one condition, this already benefits from nested storage because it correctly scopes the match to individual review entries rather than treating the ratings array as one undifferentiated pool.
The pattern that truly showcases why nested exists is the multi-condition nested query, where two or more conditions are combined inside the same nested query so that they must all be satisfied by the very same hidden child document — for example, “at least one review has author Alice and rating 1,” which is exactly the scenario a plain object field cannot answer correctly.
Range conditions inside nested queries follow the same logic: a query asking for “a line item with quantity greater than 10 and price less than 50” only matches if a single nested line-item entry satisfies both bounds together, rather than one entry supplying the quantity and a different entry supplying the price.
Single-Field Match
Checks whether any nested entry has a given field value; correct even without cross-field concerns.
Multi-Field Match
Requires multiple fields to match within the same nested entry — the signature use case for nested.
Range Within an Entry
Combines numeric or date range conditions that must hold together inside one nested object.
Nested Existence Check
Confirms whether a document has any nested entries at all under a given path, regardless of their contents.
By default, the relevance score contributed by a nested query reflects the best-matching nested child document, though this scoring mode can be adjusted to instead average or sum across all matching children when that better reflects the ranking a search experience needs.
8Advantages, Disadvantages, and Trade-offs
The nested type solves a real correctness problem, but it is never free — every gain here has a matching cost.
Advantages
- Preserves exact field relationships within each object in an array, eliminating cross-object false matches
- Supports precise, per-object queries such as “author AND rating together” instead of two independent conditions
- Provides inner hits, so the application can show exactly which nested object caused a match
- Enables nested and reverse-nested aggregations for accurate statistics scoped to individual array entries
- Keeps the natural, hierarchical JSON shape developers expect, rather than forcing denormalization
Disadvantages / Trade-offs
- Every nested object becomes an additional hidden Lucene document, inflating total document count and disk usage
- Any update to a document touches the entire parent plus all nested children, which is costlier than updating a plain field
- Nested queries are inherently more expensive than plain field queries because of the internal parent-child matching step
- By default there is a hard limit on the number of nested fields per index and the number of nested objects per document, to guard against runaway document explosion
- Sorting, highlighting, and some aggregation types require special nested-aware syntax rather than working the same way as regular fields
A single parent document with a nested array of one thousand entries becomes roughly one thousand and one physical Lucene documents. Multiply that by millions of parent documents, and a modest-looking JSON payload can silently balloon an index’s real document count into the billions.
This is exactly why Elasticsearch enforces default safety limits: by default, an index allows a limited number of distinct nested fields in its mapping, and each document is capped in how many nested objects it may contain in total across all of its nested fields, both configurable but deliberately conservative out of the box.
It is worth thinking about these trade-offs in terms of the two costs they trade against each other: correctness cost and resource cost. A plain object field pays a low resource cost but risks a correctness failure that is invisible until the wrong data surfaces in production. A nested field pays a higher, but predictable and measurable, resource cost in exchange for guaranteed correctness on cross-field queries. Framed this way, the decision to use nested is really a decision about which type of failure your application can tolerate less: silent wrong answers, or higher infrastructure cost.
Choosing nested is a bit like choosing to label and separately bag every ingredient for a recipe instead of tossing them all into one shared bowl ahead of time. Labeling costs a little more time and a few more bags, but it guarantees you will never accidentally use the wrong ingredient later — a trade most careful cooks are happy to make when precision actually matters.
9Design Patterns: Nested vs. Object vs. Join
Nested is not the only way to model relationships in Elasticsearch — knowing when to reach for it, and when not to, is the real skill.
Elasticsearch offers three broad strategies for modeling “one thing that has many related things”: the plain object type, the nested type, and the separate join field (parent/child relationships across separate documents). Each strategy makes a different trade-off between correctness, query flexibility, storage cost, and update cost.
Plain Object
Best when the array either has only one entry, or when cross-field accuracy within each entry genuinely does not matter for your queries.
Nested Type
Best when you need precise, correct matching across multiple fields of the same array entry, and the array size per document stays modest.
Join Field
Best when the “child” objects are numerous, updated independently and frequently, or need to be queried and returned as standalone entities.
Denormalized Duplication
Best for read-heavy, rarely-updated data where duplicating parent fields into separate documents per relationship avoids joins entirely.
Rule of Thumb
Reach for nested only when you actually need to query across multiple fields of the same array entry together. If your queries only ever touch one field of the array at a time, a plain object — or even separate top-level arrays — is simpler and cheaper.
Problem
Modeling a large, rapidly-growing array — such as an audit trail with thousands of entries appended over a document’s lifetime — as a nested field.
Why It’s Harmful
Every single new entry forces a full reindex of the parent document and every previous nested entry, turning a cheap append into an increasingly expensive full rewrite as the array grows.
Correct Approach
Model unbounded, frequently-growing collections as separate documents linked by a shared identifier field, or use a join field, so new entries can be indexed independently without touching the parent.
Problem
Marking every object-shaped field as nested “just in case,” without checking whether any query actually needs cross-field accuracy for that field.
Why It’s Harmful
Unnecessary nested fields multiply document count and slow down both indexing and querying for no real correctness benefit, while also eating into the index’s nested-field and nested-object limits.
Correct Approach
Default to plain object mapping, and only promote a field to nested once you can point to a specific query that produces wrong results without it.
10Best Practices and Common Mistakes
Most nested-type problems in production trace back to one of a handful of recurring mistakes.
Keep Arrays Small
Nested is designed for arrays with a small, bounded number of entries per document — tens, not thousands.
Use Inner Hits Deliberately
Request inner hits only when the application genuinely needs to know which nested object matched, since they add response size and computation.
Monitor Nested Object Counts
Track how close documents are getting to the configured nested-object limit before it becomes a hard indexing failure in production.
Batch Updates Thoughtfully
Because any nested update rewrites the whole parent, batch or debounce frequent small changes to nested arrays where possible.
Writing a plain compound query with multiple conditions against fields inside a nested array, instead of wrapping them in a nested query, silently falls back to independently matching each field across any nested object — reintroducing the exact cross-object mismatch problem nested was meant to solve.
Attempting to sort parent documents by a field inside a nested array without specifying which nested object to sort by (for example, the minimum or maximum) leads to ambiguous or rejected sort requests, since Elasticsearch cannot guess which of several nested objects’ values you mean.
Reverse nested aggregations are powerful but add computational overhead; use them only when a report genuinely needs to combine nested-level and parent-level statistics in the same aggregation tree.
Teams that adopt nested fields successfully tend to treat the mapping as a living decision rather than a one-time setup step. As a dataset grows and query patterns evolve, it is worth periodically revisiting whether a field that was mapped as nested for a query that no longer exists could be simplified back to a plain object, and conversely, whether a plain object field is now being queried in ways that would benefit from nested’s cross-field guarantees.
Testing Nested Mappings Before Production
Because the correctness problem nested solves is invisible with small, tidy sample data, it is worth deliberately testing with adversarial sample documents — arrays where sibling entries share overlapping values on purpose — to confirm that cross-field queries behave as expected before real user data ever reaches the index.
11Monitoring, Metrics, and Index Health
Because nested fields inflate the real document count behind the scenes, monitoring needs to look past the numbers you might expect.
A cluster operator who only checks “how many documents did I index” can be badly misled by nested-heavy indices, since the number of logical JSON documents sent to Elasticsearch and the number of physical Lucene documents stored can differ by orders of magnitude. Monitoring dashboards should track both figures separately to understand true index size and growth trends.
Total Lucene Document Count
Includes hidden nested child documents; a sudden spike often signals an unexpectedly large nested array being indexed.
Index Size on Disk
Grows faster than expected in nested-heavy indices because every hidden child document carries its own stored fields and index structures.
Indexing Latency
Rises when updates repeatedly touch documents with large nested arrays, since each update rewrites the parent plus all its children.
Nested Object Limit Rejections
A rising count of indexing failures caused by exceeding the configured nested-object limit is an early warning of unbounded array growth.
Practical Monitoring Tip
Periodically sample documents in nested-heavy indices to check the distribution of nested array lengths; a slowly creeping maximum length is often the first sign that a “small array” assumption made during initial design no longer holds true in production.
It is also worth tracking these metrics over time rather than as a single snapshot, since the risks associated with nested fields tend to appear gradually rather than suddenly. A dataset that starts with an average of five reviews per product can, over several years of organic growth, drift toward an average of fifty or more, quietly shifting the balance of trade-offs discussed earlier in this guide without any single deployment or code change being obviously responsible.
Beyond per-index metrics, watch for cluster-wide symptoms such as rising heap usage during aggregation-heavy query periods, since nested and reverse-nested aggregations can be more memory-intensive than their flat-field equivalents when applied across very large nested arrays.
12Security Considerations
Nested fields do not introduce a new security surface by themselves, but they intersect with existing access-control and resource-protection concerns in specific ways.
When field-level security is used to hide certain fields from certain users, nested object fields must be explicitly included in those rules with their full nested path; forgetting the nested prefix can leave sensitive nested sub-fields unintentionally visible.
Without enforced limits, a malicious or careless client could submit documents with enormous nested arrays, multiplying document count and consuming disk and memory disproportionately to the apparent payload size — one reason the default nested-object caps exist and should rarely be raised carelessly.
Because nested queries are computationally heavier than plain field queries, exposing raw, unrestricted nested query construction to untrusted end users (for example, through a search box that maps directly to query syntax) can also become a denial-of-service vector, making query validation and complexity limits a sensible safeguard in public-facing search applications.
13Real-World and Industry Examples
Seeing where the nested type earns its keep in practice makes the abstract chapters above concrete.
E-commerce Product Catalogs
Online retailers commonly model product variants — combinations of size, color, and stock-keeping unit — as nested objects, so a search for “size Large AND color Red AND in stock” correctly matches only variants where all three conditions hold for the same variant, not any combination scattered across different variants of the same product.
Review and Rating Platforms
Platforms that let one product carry many independent reviews, each with its own reviewer, rating, and date, use nested fields so that filtering “reviews from verified purchasers with a rating below 2” reflects genuine single-review combinations rather than mixed-and-matched fields from unrelated reviews.
Human Resources and Skill Matching
HR and recruiting search systems that store each candidate’s skills as objects with a skill name and a proficiency level use nested mapping to ensure that “Expert in Python” genuinely reflects one skill entry, rather than incorrectly matching a candidate who is merely a Beginner in Python but Expert in an unrelated skill.
Financial Transaction Line Items
Invoice and order systems that store multiple line items per transaction, each with its own product, quantity, and price, rely on nested fields so that “line item with quantity greater than 10 and price under a threshold” reflects a genuine single line item rather than a mismatched combination.
Real Estate and Property Listings
Property search platforms that let a single listing include multiple room entries, each with a room type and a size, use nested fields so a search for “bedroom larger than 200 square feet” matches only listings where a genuine bedroom entry meets that size, rather than mixing a small bedroom with a large but unrelated living room in the same listing.
Logistics and Fleet Tracking
Fleet management systems that record multiple stop events per delivery route, each with a location and a timestamp, rely on nested fields so that “stop at Warehouse B after 3pm” reflects one genuine stop event, rather than any warehouse name paired with any timestamp from anywhere else on the same route.
Across every one of these examples, the underlying shape of the problem is identical: a single parent entity carries a list of related sub-entities, and at least one query in the application needs to treat two or more fields of the same sub-entity as a single, indivisible unit. Recognizing that shape in a new project — before the mapping is chosen and data starts flowing in — is the single most useful skill this guide can leave you with.
It is also useful to notice what these examples have in common on the other side of the trade-off: in each case, the array of sub-entities per parent stays within a reasonable, bounded range — a handful of room entries per listing, a manageable number of stops per route, a modest count of reviews per product in any single time window. None of these examples involve an array that grows without bound for the lifetime of the parent document, which is exactly the condition under which nested fields continue to perform well over time.
14Frequently Asked Questions
A handful of questions come up again and again once teams start working with nested fields in real projects.
No. Both accept the same JSON shape, but a plain object field flattens array entries and loses the relationships between fields in the same entry, while a nested field stores each entry as its own hidden document, preserving those relationships.
No. The cross-object mismatch problem only appears when an array has more than one entry; a single-entry array behaves identically whether mapped as object or nested, so plain object mapping is simpler and cheaper in that case.
Yes, but each nested array must be queried with its own separate nested query clause targeting its own path; a single nested query only ever scopes to one nested path at a time.
Elasticsearch enforces a configurable cap on the total number of nested objects a single document may contain across all its nested fields; exceeding that cap rejects the indexing request until the array is trimmed or the limit is deliberately raised.
No. Any change to a nested field requires reindexing the entire parent document along with all of its nested children as a single atomic write, because they must stay physically adjacent inside the same Lucene segment.
Not by default; sorting on a nested field requires specifying nested-aware sort options, such as which nested object’s value should represent the document — typically the minimum or maximum among its nested entries.
Nested provides no benefit for a single, non-array object, since there is no cross-object mismatch to prevent; its value comes specifically from correctly isolating multiple entries in an array.
Yes, nested fields can be declared inside other nested fields to model multi-level hierarchies, though each additional level increases both query complexity and the physical document multiplication described earlier, so deep nesting should be used sparingly.
Yes, because the underlying physical storage layout is completely different between the two types, changing an existing field’s mapping from object to nested requires creating a new index with the updated mapping and reindexing all existing documents into it.
The nested data type and its query syntax are part of Elasticsearch’s core query language, so any official or community client library that can send raw query bodies can construct nested queries, though some higher-level query builder helpers vary in how directly they expose nested-specific options.
15Summary and Key Takeaways
The nested data type exists to solve one specific, recurring problem: arrays of objects, when mapped as plain objects, lose the relationships between fields belonging to the same entry, letting queries wrongly mix and match values across unrelated array items. By storing each nested entry as its own hidden Lucene document, physically adjacent to its parent, Elasticsearch preserves those relationships and enables precise, correct queries, inner hits, and scoped aggregations — at the cost of higher document counts, heavier updates, and more expensive queries. Used deliberately, on modestly-sized arrays where cross-field accuracy genuinely matters, nested is one of the most powerful correctness tools in Elasticsearch’s modeling toolbox.
The decision to reach for nested should always be traceable back to a concrete query requirement, not adopted as a default habit or applied uniformly across every object-shaped field in a schema. A team that internalizes the distinction between “an array exists” and “an array’s fields must be matched together” will consistently make better modeling decisions than one that treats nested as either an automatic best practice or an obscure feature to avoid altogether. With the internal mechanics, trade-offs, and query patterns covered in this guide, that distinction should now be a straightforward one to recognize in any future Elasticsearch schema you design.
Key Takeaways
- The core problem — Plain object fields flatten arrays of objects, merging their fields into shared arrays and losing which value belonged to which original entry.
- The core fix — Nested fields store each array entry as its own hidden Lucene document, kept physically adjacent to its parent, preserving true field relationships within each entry.
- Storage impact — Every nested object adds one additional physical document, so large arrays can silently multiply an index’s real document count.
- Update cost — Any change to a nested field forces a full rewrite of the parent document and all of its nested children together; there is no partial nested update.
- Query mechanics — Nested queries scope matching to individual hidden child documents, and inner hits reveal exactly which entry matched.
- When to use it — Reach for nested only when queries genuinely need cross-field accuracy within the same array entry, not for every object-shaped field by default.
- Operational care — Monitor nested object counts and array sizes over time, since unbounded growth turns a design convenience into a performance and reliability risk.