The Nested Query in Elasticsearch
The one query clause that knows how to ask "does a single item in this list satisfy all of these conditions together" — and actually get the truthful answer.
Imagine asking a librarian to find you a folder that contains a page written by “Alice” with the number “1” on it — and having her hand you a folder where Alice wrote a completely different page, and the number 1 appears on someone else’s page entirely. That mismatch is exactly what happens when an ordinary query is pointed at a nested field. The nested query exists to fix precisely this failure: it is the query clause that understands folders, not just loose pages. In this guide we will unpack exactly what a nested query is, how it is built, how it executes internally, and how to use it correctly and efficiently.
1What Is a Nested Query?
Before defining the query, we need one quick reminder about the data type it is built to search.
A nested query is a special query clause in Elasticsearch used to search fields that have been mapped with the nested data type. Recall that a nested field takes an array of objects and, instead of flattening every object’s properties into shared arrays, stores each object as its own small, hidden document living right alongside its parent. A nested query is the only query clause that knows how to reach into those hidden documents and search them correctly, one at a time, without ever mixing values from two different array entries.
Think of a nested field as a filing cabinet where every array entry gets its own sealed envelope inside a shared folder. A normal query can only see the outside of the folder and would happily mix up envelopes. A nested query is a special instruction that says: “open one envelope at a time, and only count it if everything I asked for is true inside that single envelope.”
The defining feature of a nested query is that every condition placed inside it must be satisfied by one single hidden child document — not scattered across several. This single rule is what makes nested queries fundamentally different from, and more precise than, an ordinary compound query built from must or filter clauses pointed at the same fields.
It helps to think of a nested query as a kind of scoped sub-search that happens entirely within the boundaries of one nested field’s hidden documents, before its result is ever handed back up to the parent-level search. From the outside, a nested query behaves like any other query clause — it produces a match or no match, and optionally a relevance score — but internally, it is running its own miniature search restricted to a specific group of hidden documents, one parent at a time.
A nested query is not a separate query syntax or a different way of writing conditions — inside it, you use exactly the same match, term, range, and other query clauses you would use anywhere else in Elasticsearch. The only thing that changes is the scope those clauses are evaluated against.
Nested Query
A query clause that scopes matching to individual hidden child documents under a specific nested path.
Path
The name of the nested field being searched, telling Elasticsearch which group of hidden documents to look inside.
Inner Query
The condition or combination of conditions that must all be true within a single nested object.
Inner Hits
An optional feature that returns the exact nested object that caused the match, not just the parent document.
2Why an Ordinary Query Cannot Be Trusted Here
Understanding the failure mode a nested query prevents is the fastest way to understand why it exists at all.
Suppose a product document contains a nested reviews field, with entries for several different reviewers and their ratings. If you write an ordinary compound query asking for “author is Alice” and, separately, “rating is 1,” pointed directly at the review sub-fields without wrapping them in a nested query, Elasticsearch will search each condition independently across all hidden review documents under that product and simply confirm that both conditions were true somewhere among them — not necessarily in the same review.
Without a nested query, a search for “Alice’s 1-star review” can incorrectly match a product where Alice gave 5 stars and a completely different reviewer gave 1 star — because nothing forces the two conditions to be checked against the very same review.
It is like asking “is there a red car in the parking lot, and is there a car with a broken headlight in the parking lot,” and being told yes to both — without ever confirming the red car is the one with the broken headlight. A nested query is the version of the question that insists both facts describe the exact same car.
This failure is especially dangerous because it does not throw an error or produce an empty result — it produces a result that looks completely normal. The search returns a document, a user clicks into it expecting to see Alice’s harsh review, and instead finds a five-star review from Alice sitting next to a scathing one-star review from someone else entirely. Nothing in the interface signals that anything went wrong; the mismatch is silent by nature.
| Query Style | Behavior Against Nested Fields |
|---|---|
| Ordinary compound query (no nested wrapper) | Confirms each condition independently anywhere among all hidden child documents |
| Nested query | Confirms all conditions together within one single hidden child document |
The nested query clause is Elasticsearch’s answer to this exact gap. It does not change how the data is stored — that decision was already made back when the field was mapped as nested — but it changes how the search engine is instructed to interpret conditions aimed at that field, restoring the “same object” guarantee that a plain compound query cannot provide.
It is also worth noting that this failure mode is not unique to text-matching conditions — it applies equally to numeric ranges, date comparisons, and exact-value filters. A range condition asking for “quantity above 10” combined separately with “price below 50,” aimed at a nested line-items field without a nested query wrapper, faces the exact same risk: the two numeric facts can be pulled from two completely different line items on the same order, producing a match that has no basis in any single real line item.
A Quick Way to Spot the Risk
Any time a search requirement can be phrased with the word “and” describing two or more properties of “the same” array entry — the same review, the same line item, the same skill — that requirement needs a nested query. If the properties genuinely do not need to belong to the same entry, an ordinary compound query is enough.
3Anatomy of a Nested Query
A nested query is built from a small, fixed set of parts, each with a distinct job.
Path
Identifies which nested field’s hidden documents should be searched — required, and must match a field actually mapped as nested.
Query
The condition, or combination of conditions, that must hold true within a single nested document under that path.
Score Mode
Controls how the relevance scores of multiple matching nested documents are combined into the parent’s overall score.
Inner Hits
An optional block that, when present, asks Elasticsearch to also return the specific nested object or objects that matched.
Score Mode in Plain Language
When more than one hidden child document under a path matches the inner query, Elasticsearch needs a rule for turning several relevance scores into one overall contribution to the parent document’s score. The available modes let you choose the highest matching score among all matching children, the lowest, the average across all of them, the sum of all of them, or to ignore scoring altogether and treat the nested query purely as a yes-or-no filter.
| Score Mode | What It Represents |
|---|---|
| Max (default) | Uses the single best-matching nested object’s score to represent the whole match |
| Min | Uses the weakest-matching nested object’s score, favoring documents where every entry matches well |
| Sum | Adds together the scores of every matching nested object, favoring documents with many matches |
| Avg | Averages the scores across every matching nested object |
| None | Ignores scoring entirely and simply treats the condition as a true-or-false filter |
An optional setting lets a nested query quietly return no matches, instead of an error, when it is run across an index or a set of indices where the target path is not mapped as nested at all — useful when the same query needs to run safely across a mixed set of indices.
Putting the Pieces Together
A complete nested query is really just these four pieces combined: point at a path, describe what must be true inside one entry under that path, decide how multiple matches should affect scoring, and optionally ask for the exact matching entries to be returned alongside the parent.
Because the inner query section accepts any ordinary query clause, it can itself be a compound query built from multiple conditions — a bool query with several must and should clauses, for instance — as long as every one of those inner conditions is still being evaluated against fields belonging to the same nested object. This is what makes a nested query flexible enough to express fairly rich per-entry conditions, such as “author is Alice, rating is below 3, and the review text mentions a specific keyword,” while still preserving the same-object guarantee for all three conditions at once.
The path given to a nested query must exactly match the dotted field name as declared in the mapping; a typo, a missing prefix for a multi-level nested structure, or a reference to the wrong nested field entirely will either error out or, depending on settings, simply return no matches with no further explanation.
4Architecture: Where the Nested Query Fits in Execution
To understand how a nested query runs efficiently, we need to revisit how nested data is physically stored.
Recall that nested fields store each array entry as its own small Lucene document, kept physically adjacent to its parent document within the same segment. A nested query is built specifically to take advantage of this adjacency: rather than scanning the whole index for candidate parents and then separately checking children, it works the other way around, first finding matching hidden child documents and then walking directly to the parent that sits right next to them in the block.
graph TD
P[Parent Document: Product 42] --> C1[Child: review by Alice, rating 1]
P --> C2[Child: review by Bob, rating 5]
P --> C3[Child: review by Carol, rating 4]
Q[Nested Query: author=Alice AND rating=1] -.searches.-> C1
C1 -.adjacent, walk to.-> P
P --> R[Returned as a match]
This design is what allows nested queries to avoid the kind of expensive, index-wide join that a naive implementation would otherwise require. Because Lucene guarantees the block ordering described earlier — child documents always sit immediately before their parent — the query engine can locate a parent from a matching child using a simple, fast internal lookup rather than a broader scan across unrelated parts of the index.
A nested query can only run this efficiently because the field was declared as nested in the mapping ahead of time; the query has no way to retroactively “discover” hidden child documents that were never created because the field was left as a plain object.
The same architecture also explains a limitation worth remembering early: a nested query can only search within one nested path at a time. If a document has two separate nested fields — say, reviews and images — a single nested query cannot combine conditions from both into one inner match; each nested path requires its own separate nested query clause, later combined at the parent level using an ordinary bool query.
This architectural choice is not an arbitrary restriction; it follows directly from how hidden child documents are tagged and grouped. Each hidden child document carries metadata identifying exactly one nested path, so there is no single hidden document that could ever represent “an entry from reviews and an entry from images at once” — the two groups of hidden documents are entirely separate populations sitting in the same physical neighborhood as their shared parent, but never merged with each other.
graph TD
P[Parent: Product 42] --> R1[Review child 1]
P --> R2[Review child 2]
P --> I1[Image child 1]
P --> I2[Image child 2]
NQ1[Nested Query path=reviews] -.scopes only.-> R1
NQ1 -.scopes only.-> R2
NQ2[Nested Query path=images] -.scopes only.-> I1
NQ2 -.scopes only.-> I2
5Internal Working: Executing a Nested Query Step by Step
Here is what actually happens, in order, when Elasticsearch receives a nested query.
Path Validation
Elasticsearch checks that the given path is actually mapped as a nested field, and honors the ignore-unmapped setting if it is not.
Scope Restriction
The search is restricted so that only hidden child documents tagged with the given nested path are considered candidates for the inner query.
Inner Query Evaluation
Each candidate hidden child document is evaluated against the inner query’s conditions, exactly as if it were a standalone document being searched on its own.
Parent Resolution
Every matching child document is resolved back to its adjacent parent document using the block-ordering guarantee described earlier.
Score Combination
If multiple children under the same parent match, their individual scores are combined into one contribution using the chosen score mode.
Optional Inner Hits Collection
If inner hits were requested, the specific matching child document or documents are captured so they can be attached to the final response.
sequenceDiagram
participant Client
participant ES as Query Engine
participant Lucene as Lucene Segment
Client->>ES: Nested query on path "reviews"
ES->>Lucene: Restrict scope to reviews children
Lucene-->>ES: Candidate child documents
ES->>ES: Evaluate inner query per child
ES->>Lucene: Resolve matching children to parents
ES->>ES: Combine scores using score_mode
ES-->>Client: Parent documents (with inner hits if requested)
It is worth dwelling briefly on step four, parent resolution, since it is the step that most clearly distinguishes a nested query’s execution from a naive join. Rather than performing a lookup against an index or a separate data structure to find “which parent owns this child,” the query engine relies purely on the fixed physical ordering established at indexing time: because every block of hidden children is guaranteed to sit immediately before its parent within the same segment, walking to the parent from a matching child is a short, local step rather than a search of its own.
This also explains why nested queries remain efficient even as an index grows very large in terms of total document count: the cost of resolving a matching child to its parent does not grow with the size of the whole index, only with the local structure of that one parent’s block, which stays constant regardless of how many other parents and their own nested children exist elsewhere in the index.
6Data Flow: Combining Nested Queries With Everything Else
Nested queries rarely live alone; they are usually one clause among several in a larger search request.
A nested query behaves like any other query clause once it produces its yes-or-no match and its score: it can be placed inside a bool query’s must, filter, should, or must_not sections, sitting alongside ordinary conditions on the parent document’s own fields. This is what allows a single search request to combine “category is Electronics” (a parent-level condition) with “at least one review has author Alice and rating 1” (a nested condition) into one coherent query.
flowchart LR
B[Bool Query] --> M1[must: category = Electronics]
B --> M2[must: nested query on reviews]
M2 --> I1[author = Alice]
M2 --> I2[rating = 1]
B --> F[Final match: parent satisfies both top-level and nested conditions]
When two separate nested fields need to be searched in the same request — for example, requiring both a matching review and a matching image tag — each nested path gets its own nested query clause, and the two clauses are then joined together using an ordinary bool query at the parent level, since a single nested query can never reach across two different paths at once.
Placing two separate conditions on two different nested paths inside the same bool query does not require them to relate to each other in any way — a matching review and a matching image tag can come from entirely different, unrelated array entries, which is usually exactly what is intended, but is worth being deliberate about.
Multi-level nesting follows the same joining principle one level deeper: when a nested field itself contains another nested field, the inner nested query is placed inside the outer nested query’s own inner query section, with its own separate path pointing to the deeper level, so that conditions can be scoped precisely at whichever level of the hierarchy they belong to.
A practical example makes this concrete: imagine an order document with a nested line_items field, and each line item itself has a nested discounts field listing multiple discount codes applied to that specific item. A search for “a line item where a specific discount code was applied and the resulting price is below a threshold” requires an outer nested query scoped to line_items, containing an inner nested query scoped to line_items.discounts, with the price condition sitting in the outer query and the discount-code condition sitting in the inner one — each condition anchored precisely to the level of the hierarchy where it actually belongs.
The bool query clauses used inside a nested query’s inner section — must, should, filter, and must_not — behave exactly as they do anywhere else in Elasticsearch; the only difference is that every one of them is being evaluated against the fields of a single hidden child document rather than the top-level document.
7Inner Hits: Seeing Exactly What Matched
A nested query alone tells you a parent matched; inner hits tell you which specific entry is responsible.
Without inner hits, a nested query’s result looks identical to any other query’s result: a list of matching parent documents, each returned in full, with no indication of which review, line item, or skill entry actually satisfied the inner condition. For many applications this is not enough — a review platform, for instance, usually wants to display the specific matching review to the user, not force them to scan the whole list themselves.
A nested query without inner hits is like being told “yes, one of the folders in this drawer has the page you wanted” without being told which folder or which page. Inner hits is the librarian pulling out that exact page and handing it to you directly.
When inner hits are requested alongside a nested query, Elasticsearch attaches a separate section to each matching parent document in the response, containing the specific nested object or objects that satisfied the inner query, along with their own individual relevance scores. This lets an application highlight precisely which review, line item, or skill entry drove the match, rather than presenting the whole parent and leaving the user to guess.
Highlighting
Inner hits can be combined with highlighting to show exactly which words inside the matching nested object triggered the match.
Sorting Within Inner Hits
The set of matching nested objects returned by inner hits can be sorted independently of the outer query’s sort order.
Pagination Within Inner Hits
When many nested objects under one parent match, inner hits supports its own offset and size controls to page through them.
Naming
Inner hits blocks can be given explicit names, which matters when a single request nests inner hits under more than one path.
Inner hits add extra computation and response payload size, so they are worth requesting only when the application genuinely needs to know which specific nested object matched, rather than being included by habit on every nested query.
Inner hits also carry their own independent highlighting and sorting configuration, separate from the outer query’s settings, which means an application can, for example, sort the outer results by overall relevance while still sorting the inner hits within each result by rating or date, tailoring the presentation of nested entries to whatever makes sense for the specific feature being built.
A Concrete Inner Hits Scenario
A product page that highlights “reviews matching your search” alongside the product itself is a textbook inner hits use case: the nested query finds products with at least one matching review, and inner hits supplies the exact review text, rating, and author to render directly under that product, without any separate follow-up query needed.
8Nested Query vs. Nested Aggregation
These two features share a name and a mental model, but they answer very different questions.
A nested query answers a yes-or-no question about parent documents: “does this parent have at least one nested entry matching these conditions?” A nested aggregation, by contrast, answers a statistical question scoped to the nested entries themselves: “across all nested entries under this path, what is the average, count, minimum, or maximum of a given field?” The two can be used independently or combined in the same request, but they are solving fundamentally different problems.
| Aspect | Nested Query | Nested Aggregation |
|---|---|---|
| Purpose | Filters or scores parent documents | Computes statistics across nested entries |
| Scope of Result | Parent documents, optionally with inner hits | Aggregation buckets or metrics, not full documents |
| Typical Use | “Find products with a 1-star review from Alice” | “What is the average rating across all reviews?” |
| Returning to Parent Scope | Not applicable — already parent-scoped | Requires a reverse nested aggregation |
The two frequently appear together in a single search request: a nested query narrows down which parent documents are relevant in the first place, while a nested aggregation, computed independently within the same request, reports statistics about the nested entries across the matching set — for example, finding products with at least one critical review, while also reporting the overall average rating across every review on those same products.
9Advantages, Disadvantages, and Trade-offs
A nested query buys correctness, but that correctness is not free at query time.
Advantages
- Guarantees that all inner conditions are checked against the exact same nested object, eliminating cross-object false matches
- Supports precise scoring control through score mode, tailoring relevance to how many or how well entries match
- Provides inner hits, revealing exactly which nested object caused a document to match
- Composes cleanly with ordinary bool queries, letting parent-level and nested-level conditions combine naturally
- Extends naturally to multi-level nested structures for deeply hierarchical data
Disadvantages / Trade-offs
- More computationally expensive than an equivalent plain field query, due to the extra child-to-parent resolution step
- Cannot combine conditions from two different nested paths within a single nested query clause
- Requires the target field to already be mapped as nested; it cannot be applied retroactively to a plain object field without reindexing
- Inner hits and highlighting add response size and processing time when requested unnecessarily
- Sorting and certain aggregation types require nested-aware syntax rather than working identically to plain fields
Because a nested query evaluates the inner condition against every candidate hidden child document under a path, the cost of the query grows with the number of nested entries per parent document, making very large nested arrays a performance concern independent of the storage concerns discussed for the nested data type itself.
It is useful to frame this trade-off the same way as the underlying nested data type itself: a nested query trades a modest, predictable amount of extra computation for a guarantee that would otherwise be impossible to obtain from a flattened representation of the same data. Teams that understand this trade-off tend to reach for nested queries confidently exactly where the correctness guarantee matters, while staying alert to array size as the main lever affecting how expensive that guarantee becomes in practice.
Checking each envelope individually inside a folder takes longer than glancing at a single shared summary sheet — but the summary sheet cannot tell you, with certainty, which envelope a fact actually came from. The extra time spent opening envelopes one by one is the price of that certainty, and it is a price that grows the more envelopes the folder holds.
10Design Patterns and Anti-patterns
A handful of recurring shapes cover most real nested-query use cases — and a handful of anti-patterns cover most of the mistakes.
Single-Entry Precision Filter
Using a nested query to confirm one entry satisfies several conditions together, such as author and rating.
Existence Check
Using a nested query with a broad inner condition simply to confirm that at least one entry exists matching a general criterion.
Multi-Path Combination
Combining separate nested queries on different paths inside one bool query to require matches across independent nested fields.
Query Plus Inner Hits
Pairing a nested query with inner hits when the application needs to display the specific matching entry to the user.
Problem
Writing an ordinary compound query with conditions aimed at fields inside a nested array, forgetting to wrap them in a nested query clause.
Why It’s Harmful
This silently reintroduces the cross-object mismatch problem that the nested mapping was specifically designed to prevent, producing results that look plausible but are factually wrong.
Correct Approach
Always wrap any condition touching fields inside a nested array in a nested query with the correct path, even when only a single condition is involved, to keep the intent explicit and future-proof against added conditions later.
Problem
Requesting inner hits with large page sizes or on every query by default, regardless of whether the application actually displays the matching nested entries.
Why It’s Harmful
This inflates response payload size and query cost across every search request, even for the majority where the extra detail is never used or displayed.
Correct Approach
Request inner hits only on the specific queries where the matching nested object needs to be shown, and keep their size limits tight to only what the interface can realistically display.
Problem
Attempting to express “condition A on path X and condition B on path Y must refer to the same real-world entity” using two separate nested queries.
Why It’s Harmful
Two separate nested queries on two separate paths have no way to guarantee their matches correspond to the same conceptual entity, since each nested path is scoped and resolved independently.
Correct Approach
If two properties genuinely need to be matched together as one unit, they belong inside the same nested object under a single path, not split across two separate nested fields.
Before writing a nested query, it is worth re-confirming the mapping actually matches the query’s assumptions: a quick check of whether the target path is genuinely declared as nested, rather than assumed to be, saves the confusion of a query that silently returns nothing because the underlying field was never mapped the way the query expects.
11Best Practices and Common Mistakes
Small habits around how nested queries are written and combined make a large difference in both correctness and performance.
Choose Score Mode Deliberately
Pick a score mode that matches the ranking behavior your search experience actually needs, rather than leaving the default unexamined.
Prefer Filter Context When Possible
When relevance scoring from the nested condition is not needed, use score mode none and place the nested query in a filter context for better performance.
Name Inner Hits in Complex Queries
Give inner hits explicit names whenever a request includes more than one, so the response clearly separates matches from different nested paths.
Test With Overlapping Data
Validate nested query correctness using sample data where sibling entries deliberately share overlapping values, to confirm no cross-object matching slips through.
Attempting to sort search results by a field inside a nested array without telling Elasticsearch which nested object’s value to use — typically the minimum or maximum among matching entries — leads to ambiguous or rejected sort requests.
When nested fields are nested within nested fields, pointing an inner nested query at the wrong level’s path is a frequent source of queries that silently return no matches, since the path must exactly match how deep the target field truly sits.
Because nested queries already carry extra execution overhead, keeping the inner query itself simple and well-targeted helps keep overall query latency predictable, especially on nested fields with large arrays.
12Performance, Monitoring, and Metrics
Nested queries are efficient by design, but that efficiency depends on assumptions worth monitoring over time.
The performance of a nested query is closely tied to how many hidden child documents exist under the target path per parent document, since the inner condition must be evaluated against each candidate before any parent resolution can happen. A dataset that starts with a handful of entries per parent and later grows into the hundreds or thousands can see nested query latency rise correspondingly, even if the query itself never changes.
Query Latency by Path
Tracking latency specifically for requests using nested queries against a given path helps isolate slowdowns tied to array growth.
Inner Hits Response Size
Growing response payload sizes from inner hits can signal either genuinely large result sets or overly broad inner hit requests.
Cache Hit Rate on Filter Context
Nested queries used in filter context with score mode none can benefit from caching; a low hit rate may indicate overly specific or highly variable queries.
Nested Array Length Distribution
Sampling the typical and maximum number of entries per nested path over time reveals whether query cost is likely to keep climbing.
A Useful Operating Habit
Whenever a nested query’s latency is investigated, check the nested array size distribution for the relevant path alongside the query itself; a slow nested query is very often explained by a small number of parent documents carrying unusually large arrays rather than by the query’s structure.
It is also worth distinguishing between latency caused by the nested query itself and latency caused by other clauses running alongside it in the same bool query. Isolating a nested query by running it on its own, without the surrounding conditions, is a quick way to confirm whether it is genuinely the bottleneck before spending time optimizing the wrong part of a search request.
13Security Considerations
Nested queries interact with a few existing security concerns in ways worth calling out explicitly.
When field-level security restricts visibility of certain fields, rules covering fields inside a nested path must reference the full nested path explicitly, since a rule written only for the top-level field name may not apply as expected to nested sub-fields.
Exposing raw nested query construction to untrusted end users — for example, through an interface that maps user input directly into query bodies — can allow expensive, deeply nested, or overly broad inner queries to be submitted, creating a resource-exhaustion risk on paths with large arrays.
Because inner hits can expose specific nested objects that a user might not otherwise be authorized to see individually, applications that combine nested queries with field-level or document-level security should verify that inner hits results are filtered through the same access rules as the rest of the response, rather than assuming that document-level authorization alone is sufficient.
A related consideration applies to logging and auditing: because nested queries can express fairly specific conditions about individual array entries, query logs that capture full request bodies may end up recording sensitive details — such as a specific reviewer’s name paired with a specific rating, or a specific employee’s exact skill level — that would otherwise only be visible through normal search results. Teams operating in regulated environments should treat nested query logs with the same care as the underlying data they describe.
14Real-World and Industry Examples
Seeing nested queries at work across different domains makes their value concrete.
E-commerce Variant Filtering
An online store search for “size Large, color Red, in stock” against a nested variants field uses a nested query to guarantee all three conditions describe one genuine variant, with inner hits used to highlight exactly which variant to add to the cart.
Review Moderation Dashboards
A moderation tool searching for “reviews flagged as abusive by a specific reviewer” relies on a nested query so that the flag and the reviewer identity are confirmed to belong to the same review, with inner hits surfacing the exact review text for a moderator to act on.
Recruiting and Skill Matching
A candidate search for “Expert level in Python” against a nested skills field uses a nested query to ensure the proficiency level genuinely applies to Python, rather than matching a candidate who is an Expert in an unrelated skill and merely a Beginner in Python.
Order Management Systems
A search for orders containing “a line item for Product A with quantity above 10” uses a nested query on the order’s line-items field so the product and quantity conditions are confirmed against the same genuine line item, with a bool query combining this alongside parent-level conditions like order status.
Across each of these examples, the nested query is doing the same job: enforcing that several conditions describe one real entity within an array, not an accidental combination stitched together from unrelated entries. That single guarantee is the entire reason the clause exists, however different the surrounding application might look.
What varies across these examples is not the underlying mechanism but the stakes attached to getting it wrong. A miscombined product review is a minor annoyance to a shopper; a miscombined line item in an order system can mean shipping the wrong quantity of the wrong product; a miscombined skill match in recruiting can mean overlooking or wrongly surfacing a candidate. The nested query’s correctness guarantee matters more, not less, as the real-world consequences of a wrong match grow more serious — which is exactly why it is worth taking seriously even in domains that seem, at first glance, low-stakes.
15Frequently Asked Questions
A short set of questions that come up repeatedly once teams start writing nested queries in real projects.
No, a nested query requires the target path to be mapped as the nested data type; running it against a plain object field either returns an error or, with ignore-unmapped enabled, silently matches nothing.
No, a single nested query is always scoped to one path; searching across two nested fields requires two separate nested query clauses combined together with an ordinary bool query.
Only if a score mode other than none is used; setting score mode to none turns the nested query into a pure true-or-false filter that does not contribute to relevance scoring.
No, inner hits is entirely optional; a nested query works perfectly well on its own to filter or score parent documents, with inner hits added only when the specific matching entry needs to be returned.
The inner nested query is placed inside the outer nested query’s own inner query, with its own separate path describing the deeper level, so each level of the hierarchy is scoped by its own nested query.
The most common causes are an incorrect path string that does not exactly match the mapped nested field name, or a field that was mapped as a plain object rather than nested, both of which prevent the nested query from finding any hidden child documents to search.
Yes, when used in filter context with score mode none, nested queries can benefit from Elasticsearch’s filter caching just like other non-scoring queries, improving performance for frequently repeated searches.
Yes, the inner query section of a nested query accepts any ordinary query type, including full-text match queries, so a nested query can search for specific words inside a nested text field while still requiring other conditions to hold on the same entry.
No, a nested query considers all hidden child documents under a path regardless of their original array position, since matching is based purely on which entries satisfy the inner condition, not on where they appeared in the source array.
16Summary and Key Takeaways
A nested query is the query clause built specifically to search fields mapped as the nested data type, guaranteeing that every condition inside it is checked against one single hidden child document rather than scattered across unrelated array entries. It is built from a path identifying which nested field to search, an inner query describing what must be true within one entry, a score mode controlling how multiple matches combine into relevance, and an optional inner hits block that reveals exactly which entry matched. Used correctly — one path per clause, combined through ordinary bool queries at the parent level, and paired with inner hits only when genuinely needed — the nested query restores the correctness that a plain compound query cannot guarantee against arrays of objects, at a query-time cost that scales with how large those arrays grow.
The broader lesson underlying this entire guide is that correctness in search systems is rarely automatic once data takes on any kind of internal structure. Whenever a document contains a list of things, and more than one property of those things matters to a query at once, it is worth stopping to ask whether an ordinary query can actually answer that question truthfully, or whether the nested query’s stricter, same-object guarantee is required. That single habit of pausing to ask the question is often the difference between a search feature that works and one that quietly, invisibly, gets some answers wrong.
As a final practical note, treat the nested query and the nested mapping decision as two halves of one design choice, not two independent steps. A field mapped as nested with no query ever taking advantage of its cross-field guarantees gains nothing from the extra storage cost, while a query attempting nested-style precision against a field that was never mapped as nested cannot succeed no matter how carefully it is written. Getting real value from this feature means making both decisions together, with the same specific query requirement in mind from the start.
Key Takeaways
- Core purpose — A nested query ensures multiple conditions are all satisfied by the same single hidden child document, not different ones.
- Required setup — The target field must already be mapped as the nested data type; the query cannot retroactively apply nested behavior to a plain object field.
- One path per clause — A single nested query only ever scopes to one nested path; multiple paths require separate clauses joined by a bool query.
- Score mode matters — Choosing max, min, sum, avg, or none shapes how multiple matching entries influence the parent’s relevance score.
- Inner hits reveal the match — Request inner hits only when the application needs to display exactly which nested entry matched, since it adds cost.
- Performance scales with array size — Nested query cost grows with the number of entries per parent under the target path, making array size worth monitoring.
- Distinct from nested aggregations — A nested query filters or scores parent documents; a nested aggregation computes statistics across nested entries, and the two solve different problems.