AEM ENGINEERING / 003

Why Is This AEM Query Traversing the Repository?

Learn why AEM Oak queries fall back to repository traversal, how to read query plans and index selection, and design queries and indexes for performance.

SHARE
LinkedIn X Facebook Threads

Topic map

Follow the query plan

Diagnosing Oak query traversal in AEM

  1. 01Query
  2. 02Constraints
  3. 03Planner
  4. 04Index / scan
  5. 05Results

SYSTEM OVERVIEW

SYSTEM / FLOW

The planner chooses among eligible paths.

Conceptual query execution. An index definition is not proof that a particular query will select it.

INDEXED PATHQuery constraintsEligible indexEstimated costIndexedcandidatesTRAVERSAL PATHQuery constraintsNo preferableindexRepository scanFilter candidatesCOMBINED PATHRead resultsInspect plan +work performed

Indexed path

  1. Query constraints
  2. Eligible index
  3. Estimated cost
  4. Indexed candidates

Traversal path

  1. Query constraints
  2. No preferable index
  3. Repository scan
  4. Filter candidates

Combined path

  1. Read results
  2. Inspect plan + work performed

THIS ARTICLE EXPLORES

  1. Read the selected plan before adding an index.
  2. Separate query eligibility from index cost.
  3. Validate against representative repository content.

01 / INTRODUCTION

Introduction

Repository traversal is not just a slow query problem. It usually signals a mismatch between the query and the available Oak indexes. The query is correct and returns the right nodes — but it gets there by walking content rather than consulting an index, and that difference is the whole performance story.

Traversal may be tolerable for a small bounded subtree and expensive for a broad one. The selected plan reflects eligible indexes and cost estimates, not simply whether an index exists. The runnable fixture below demonstrates that distinction without making a production performance claim.

This article is a diagnostic procedure for AEM developers, backend engineers and Oak practitioners: how to recognise traversal, read the execution plan, understand how Oak selects an index, and then fix the real problem by refining either the query, the index, or the search architecture behind it.

02 / WHAT IS TRAVERSAL

What is query traversal?

A JCR query in AEM is parsed by Oak's query engine, which evaluates the available indexes, estimates the cost of each, and picks the cheapest plan. If a suitable index exists, Oak reads matching entries directly from it. If no index covers the query, Oak falls back to traversal: it walks nodes under the query's path scope and evaluates the restrictions in memory.

Traversal can evaluate the query without a suitable index, but it is not an unconditional completion guarantee: configured traversal policies and read limits can reject or terminate execution. Indexed queries can also inspect many candidates or sort in memory. Inspect the plan and actual work separately.

The practical rule: traversal on a small, tightly path-restricted subtree can be acceptable; traversal across a large or unbounded scope is a latent production incident. The goal of diagnosis is to know which one you have.

  • Indexed query: Oak reads matching entries from an index — cost tied to result size
  • Traversal: Oak walks nodes under the path scope — cost tied to repository size
  • Compare actual result identities; query limits and index freshness need separate validation
  • Traversal cost grows with content, so the problem appears over time, not at launch

03 / HOW OAK CHOOSES AN INDEX

How Oak chooses an index

Oak does not guess. Each index implementation inspects the query and returns an estimated cost; the query engine selects the lowest-cost plan that can answer it. Understanding what feeds that estimate is what lets you design queries an index can actually serve.

The query shape drives everything. Property restrictions (equality on an indexed property), path restrictions (a specific subtree rather than the whole repository), node type constraints, and fulltext predicates each map to different index capabilities. A property index is suitable for supported non-fulltext restrictions such as equality; Lucene supports other query shapes depending on its definition. Do not assume a basic property index implements range ordering or relative-property restrictions.

An ineligible index reports an unusable cost. Traversal can also be selected when estimated cheaper than an eligible index. Inspect the selected plan rather than inferring missing coverage from a cost value alone.

  • Query shape: which restrictions are present and how selective they are
  • Property restrictions: verify support for the exact operator and indexed property
  • Path restrictions: scope the query to a subtree instead of the whole tree
  • Node types: nt:/sling: type constraints an index can key on
  • Fulltext constraints: contains() predicates served by a Lucene index
  • Index cost: the estimate each index returns; the engine picks the cheapest
Plan review
DimensionEvidenceFailure to investigate
EligibilityNode type, path and property constraints.Definition does not cover the query.
OrderingPlan and requested sort.Large in-memory sort after candidate selection.
SelectivityRepresentative candidate count.An indexed query still reads too much.
Index stateActual deployed definition and status.Local definition differs from the environment.

04 / COMMON CAUSES

Common causes of traversal

Most traversal reduces to a small set of recurring causes. Work through them against the specific query that is slow, not queries in general.

  • No property index exists for the property being restricted on
  • A Lucene index definition exists but does not declare the queried property
  • The query restricts on an unindexed or dynamically-named property
  • Leading-wildcard or open-ended LIKE patterns that no index can seek on
  • Broad path scope — querying from / or a very large subtree
  • OR-heavy queries where each branch needs a different index
  • Functions or expressions on a property that prevent a direct index lookup
  • Node type assumptions that do not match the indexed type
  • A stale, disabled, or misconfigured index that is not actually serving the query
  • Missing path restriction broadens the candidate scope; it does not by itself prove traversal

05 / QUERY EXAMPLES

Query examples

The executable fixture below preserves query semantics and changes only index definitions. The separate examples here illustrate query shapes to investigate; they are not captured AEM plans.

A path restriction narrows scope but does not guarantee index selection. The two SQL2 examples ask different questions and are not equivalent optimizations. Relative properties and LIKE predicates require checking the exact deployed index definition and EXPLAIN result.

05 — Query examples

text
// QueryBuilder — traversing: no path scope, unindexed property
type=cq:Page
property=jcr:content/customStatus
property.value=approved

// QueryBuilder — improved: path scope + indexed property
path=/content/site/en
type=cq:Page
property=jcr:content/customStatus
property.value=approved
// (customStatus declared in a property or Lucene index)

-- SQL2 — traversing: leading wildcard cannot seek an index
SELECT * FROM [cq:Page] AS p
WHERE ISDESCENDANTNODE(p, '/content/site')
  AND p.[jcr:content/title] LIKE '%report%'

-- SQL2 — improved: equality on an indexed property
SELECT * FROM [cq:Page] AS p
WHERE ISDESCENDANTNODE(p, '/content/site/en')
  AND p.[jcr:content/category] = 'report'

06 / EXPLAIN QUERY PLAN

Explain the query plan

Do not guess whether a query traverses — ask Oak. The query engine can explain its plan, exposing which index it selected, the estimated cost, and whether it fell back to traversal. In AEM this is available through the query tooling in the operations console and via the EXPLAIN prefix in SQL2.

Prefix a SQL2 statement with EXPLAIN to return the chosen plan instead of results. The plan names the index that will serve the query; a plan that reads [nt:base] as a traversal, or warns about traversal, is the signal to stop and look at index coverage. A healthy plan names a specific property or Lucene index and a bounded path.

Read the plan for three things: the selected index, the estimated cost or node count, and the path restriction. If the cost estimate is large or the selected 'index' is really a traversal over a base type, the query is not covered — regardless of how fast it happens to run on your current content volume.

06 — Explain the query plan

text
EXPLAIN SELECT * FROM [cq:Page] AS p
WHERE ISDESCENDANTNODE(p, '/content/site/en')
  AND p.[jcr:content/category] = 'report'

Look for, in the returned plan:
  - selected index        e.g. lucene:cqPageLucene(/oak:index/...)
  - estimated cost        optimizer estimate, not measured latency
  - traversal warning     'no proper index' / traversal over [nt:base]
  - path restriction      a bounded subtree, not /

Three controlled states

Same SQL2, same content, same result identities; only the index definitions change.

  1. 01Seed synthetic content
  2. 02Capture traversal plan
  3. 03Add wrong-property index
  4. 04Confirm traversal remains
  5. 05Add matching index
  6. 06Assert plan + results

EXECUTED SQL2 · standalone Oak fixture

sql
SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE(s, '/content/lab') AND s.[labCategory] = 'engineering'
REPRODUCIBLE LAB / SOURCE + EVIDENCE

One query, three index states

A disposable standalone Oak repository demonstrates traversal, a mismatched index, and a selected property index against the same synthetic content. Download the source and inspect the assertions.

Recorded validation:

ENVIRONMENT / RECORDED VERSIONS

Runtime
Oracle JDK 17.0.12 · macOS aarch64 · Maven 3.8.6
Repository
Standalone Oak JCR 1.88.0 · in-memory repository
Tests
JUnit Jupiter 5.10.2 · Surefire 3.2.5
Build
Java 17 compilation · Compiler 3.11.0 · Jar 3.3.0

SETUP / REQUIREMENTS

  • Install JDK 17 and Maven; confirm their selected versions. Only the recorded environment was tested.
  • Extract the ZIP and enter oak-query-traversal. Allow Maven Central dependency downloads; settings.xml contains no private repositories or credentials.
  • No AEM instance, SDK, external database or credentials are required. The test creates and shuts down its own synthetic repository.

RUN

mvn -s settings.xml -B verify

VALIDATES

  • The same SQL2 query returns exactly three fixture paths in all three states.
  • Without a matching index, both the baseline and wrong-property index plans select traversal.
  • After creating the matching synchronous property index, the plan selects /oak:index/labCategory.
  • The matching node outside /content/lab is excluded from every result set.

DOES NOT VALIDATE

  • AEM deployment, compatibility with a particular AEM version, or a production index rollout procedure.
  • Latency, speedup, scan counts, production scale, memory use or representative content distribution.
  • Lucene/fulltext, ordering, asynchronous freshness, ACL enforcement, clustering or AEM Cloud index deployment.

CAPTURED OUTPUT / EXCERPT

CHECK fixture: 100 descendants; 3 matches; 1 matching node outside scope
QUERY SELECT * FROM [nt:base] AS s WHERE ISDESCENDANTNODE(s, '/content/lab') AND s.[labCategory] = 'engineering'
BEFORE EXPLAIN
[nt:base] as [s] /* traverse
    allDescendents: /content/lab
    estimatedEntries: 1000000.0
 */
MISMATCHED INDEX EXPLAIN
[nt:base] as [s] /* traverse
    allDescendents: /content/lab
    estimatedEntries: 1000000.0
 */
AFTER EXPLAIN
[nt:base] as [s] /* property labCategory
    indexDefinition: /oak:index/labCategory
    values: 'engineering'
    estimatedCost: 6.0
 */
CHECK identical result paths: [/content/lab/item-000, /content/lab/item-001, /content/lab/item-002]
CHECK unrelated property index does not satisfy labCategory query
CHECK matching property index selected; outside-scope node excluded
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

SOURCE NOTES / VALIDATION BOUNDARY

Captured from a local Maven verify run on Oracle JDK 17.0.12, Maven 3.8.6, macOS aarch64. Query plans and CHECK lines are contiguous; the final test summary and BUILD SUCCESS are excerpts from the same successful run. Build paths, dependency download chatter and timing are omitted. No production repository was used.

estimatedEntries and estimatedCost are planner estimates, not measured rows or milliseconds. EXPLAIN computes a plan; separate result assertions execute the query.

Source hashes are checked during packaging. The test-only project may report an empty-JAR warning; source and Surefire tests are the deliverable. No public GitHub repository is claimed.

LOCAL FIXTURE ONLY · synchronous property index

java
static void addIndex(Session session, String name, String property) throws Exception {
        Node index = session.getNode("/oak:index").addNode(name, "oak:QueryIndexDefinition");
        index.setProperty("type", "property");
        index.setProperty("propertyNames", new String[] {property}, PropertyType.NAME);
        index.setProperty("reindex", true);
        session.save(); // Synchronous property indexing in this small disposable fixture only.
    }
Index decision and validation boundary
DecisionReasonBoundary
Single-property indexThe fixture filters labCategory by equality.Not a fulltext or general AEM search recommendation.
Mismatched-index controlAn unrelated index must not count as coverage.Does not enumerate every planner eligibility rule.
Synchronous local rebuildMake the small fixture deterministic after save.Not a safe production reindex procedure.
Compare result identitiesProve the selected path preserves these results.No benchmark or permission guarantee.

07 / OAK INDEXES IN AEM

Oak indexes in AEM

AEM ships on Oak with two index families you work with most: property indexes and Lucene indexes. Property indexes are synchronous and best for exact, selective restrictions on a single declared property — fast to maintain, narrow in scope. Lucene indexes are asynchronous and cover fulltext plus richer combinations of properties, at the cost of a short indexing lag and heavier definitions.

Index definitions live under /oak:index as content, which is what makes them deployable and version-controllable alongside the application. A custom index definition declares the properties it indexes, the node types it applies to, and whether it is synchronous or async. Async indexing means a newly written node becomes queryable once the background indexer processes it — dependent on indexer health and backlog, not a fixed freshness guarantee.

Be deliberate about out-of-the-box indexes. Modifying a shipped index definition can affect queries you did not write and complicate upgrades, since Adobe may change those definitions between versions. Prefer a well-scoped custom index for application-specific queries over editing an OOTB one, and treat every index change as something to validate rather than assume.

  • Property index: useful for supported selective property restrictions; this fixture tests equality
  • Lucene index: asynchronous, covers fulltext and multi-property queries
  • Index definitions are content under /oak:index — deployable and reviewable
  • Async indexing introduces a short lag before new content is queryable
  • Avoid editing OOTB index definitions; prefer scoped custom indexes

08 / UPGRADE MIGRATION ANGLE

AEM upgrade / migration angle

Traversal problems often appear without the query changing at all. A query that was indexed and fast can start traversing after an upgrade, a migration, or simply enough content growth — and because nothing errors, the regression is easy to miss until latency climbs. This is why query and index behaviour belong in the validation plan for any AEM 6.5 LTS modernization or platform migration.

Upgrades change Oak versions and sometimes OOTB index definitions. An index your query relied on may be redefined, renamed, or have different property coverage; a custom index carried over from an older line may no longer match how the new Oak plans the query. Custom code changes that alter a query's shape — a new restriction, a reordered predicate, a changed node type — can likewise move it off its index.

The underappreciated driver is content volume. A query that traverses a small subtree is invisible in testing and painful in production, so the failure often surfaces months after a release as the repository fills. Validate queries against representative content volumes, not the handful of nodes on a fresh environment.

  • Oak version changes can alter index selection and cost estimation
  • Upgrades may redefine or rename OOTB index definitions
  • Custom index definitions may no longer match a newer Oak's planning
  • Code changes that reshape a query can move it off its index
  • Content growth turns a tolerable subtree walk into a production problem

09 / SEARCH VS REPOSITORY QUERY

Search vs. repository query

Not every search belongs in Oak. JCR queries are the right tool for structured, selective retrieval — find the pages of this type under this path with this property value. They are the wrong tool for open-ended functional search: relevance ranking, faceting, typo tolerance, synonyms, aggregations and free-text exploration across large corpora.

When requirements drift toward that functional-search shape, forcing them through Oak leads to ever-broader Lucene indexes and queries that are hard to keep off traversal. A dedicated search platform such as Elasticsearch is built for exactly those access patterns, which is the architecture behind an Elasticsearch-backed AEM search: AEM remains the governed content source, content is indexed into the search system, and the application queries that system for relevance-driven results.

This is an architecture decision, not a workaround. Keep selective, structured lookups in Oak where they are cheap and transactional; move relevance-ranked, faceted, high-cardinality search to a system designed for it. Trying to serve the second category from raw JCR queries is a common root cause of unavoidable traversal.

10 / TROUBLESHOOTING FLOW

Performance troubleshooting flow

A slow query has a short, repeatable investigation. The point of the flow below is to replace guessing — adding indexes speculatively, or broadening a Lucene definition until the symptom disappears — with reading the plan and acting on what it names.

Start from the query and the plan, not from the index. Only once you know which index was selected (or that none was) do you decide whether to refine the query, extend an index, or move the use case to a search platform. Then validate the change at a representative content volume, because that is where traversal actually hurts.

10 — Performance troubleshooting flow

text
Slow query
   |
Inspect the query (shape, restrictions, path scope)
   |
Check the execution plan (EXPLAIN / query tool)
   |
Identify the selected index
   |
Traversal?  --- no --> cost acceptable at scale? --> done
   | yes
Review index coverage (property / Lucene definition)
   |
Refine the query OR the index (or move to a search platform)
   |
Validate on representative content volume

A controlled diagnosis

Change one variable and compare against the same content shape.

  1. 01Capture query
  2. 02Explain plan
  3. 03Check definition
  4. 04Measure candidates
  5. 05Refine query / index
  6. 06Revalidate load

11 / ANTI PATTERNS

Anti-patterns

Most traversal remediation goes wrong in predictable ways. Each of these makes a symptom disappear locally while degrading the platform or hiding the real cause.

  • Creating a new index for every query instead of reshaping the query to fit existing coverage
  • Broad, catch-all custom Lucene indexes that index far more than any query needs
  • Querying the full repository from / instead of restricting to a known subtree
  • Ignoring path restrictions because 'it is fast enough' on current content
  • Solving functional, relevance-driven search with raw JCR queries when a search platform fits better
  • Validating only on a small environment, so traversal never shows up before production

12 / PRODUCTION CONSIDERATIONS

Production considerations

Index and query changes are deployments with real operational cost, and they behave differently in production than on a laptop. Treat them with the same rigour as any platform change, and tie their validation to production observability so a regression surfaces as a metric rather than a support ticket.

Content scale and query frequency together decide impact: a moderately expensive query executed on every page render is a bigger problem than an expensive query run occasionally. Async Lucene indexing means a newly deployed index is not instantly populated — a reindex can be expensive on a large repository and must be planned, not triggered casually during peak load.

Validate changes safely: confirm the new plan with EXPLAIN, reindex in a controlled window, and verify against representative content volume before trusting results from a sparse environment. The goal is to know the query is indexed and bounded before it meets production traffic, not to discover it afterward.

  • Weigh query cost against execution frequency, not cost alone
  • Async indexing and reindex cost scale with repository size — plan the window
  • Confirm the post-change plan with EXPLAIN before relying on it
  • Validate on representative content volume, not a sparse instance

13 / MY PERSPECTIVE

My perspective

Treat the query and the index as one design problem. A query is only as good as the index behind it, and an index only earns its cost if real queries use it. Writing them separately — a query here, an index added reactively later — is how repositories accumulate both traversal and unused indexes at the same time.

In practice I read the plan first, every time. The plan converts 'this feels slow' into 'this query selected no index and walks /content' — a specific, fixable statement. From there the decision is honest: tighten the path and restriction, extend a scoped index, or accept that the use case is functional search and belongs in a system built for it.

The habit that pays off is validating at scale. Traversal is invisible on a fresh instance and unmistakable on a full one, so the engineering value is in testing against representative content before the regression reaches users — and in designing the query and index together so it never traverses in the first place.

14 / CONCLUSION

Conclusion

Traversal is a signal, not a verdict. It tells you the query and the available indexes have diverged — so the fix is rarely 'add an index and move on' and usually 'revisit the query shape, the index design, the content model, or the search architecture' until the two fit again.

Read the plan, name the selected index, and decide deliberately between refining the query, extending an index, and moving functional search to a dedicated platform. Done that way, a query that quietly walked millions of nodes becomes a bounded, indexed lookup — and stays one as the repository grows.

REFERENCE DESK

Sources & further verification

Product behavior should be checked against the target AEM and search-engine release. The design choices in this note are proposed assessment criteria, not vendor guarantees.

SHARE THIS NOTE

Found this useful? Share it with someone working on AEM, platform engineering or search.

SHARE
LinkedIn X Facebook Threads

CONTINUE THE THREAD

Related engineering notes

Related engineering work