Optimising AEM Query Builder for Complex Predicates

AEM Query Builder lets developers express searches as a tree of typed predicates instead of assembling JCR-SQL2 by hand. That convenience can hide an expensive execution plan: nested and/or groups, path restrictions, full-text clauses and broad cardinality estimates may reach Oak without a matching index.

Optimisation is not simply about shortening source code. It means aligning the predicate tree with Oak’s indexes, bounding result sets, measuring realistic data and moving specialised workloads out of JCR where they do not belong.

Why complex predicates become slow

Query Builder translates its predicates into a query that Oak plans and executes. The planner evaluates available indexes, estimated selectivity, property types and the expected number of results. The number of predicates in the Java code is therefore a poor guide to performance; ten tightly indexed conditions can be faster than one broad condition.

Path traversal is a frequent culprit, especially when the query covers much of the repository. Large OR groups, substring matching, unbounded hit-count calculations and deep offsets also add work. Sorting a broad result set can be costly when the sort property is not indexed.

Keep the evidence hierarchy straight. A third-party page offering an external perspective can widen the research base, but Oak query plans, index definitions and measured traces should decide every AEM change.

Designing predicates that Oak can execute

Start with selectivity. Combine conditions that meaningfully reduce the candidate set, place the most selective indexed filters first and constrain searches to the smallest practical repository path. A date range or content type is often more useful than a generic full-text condition applied across the entire site.

Choose each operation deliberately. Prefer equality for exact identifiers, range predicates for bounded values and full-text search for tokenised relevance. Substring matching is rarely a substitute for an exact lookup because it prevents effective index use. Native SQL2 can express requirements that typed predicates cannot, but it should be an intentional choice with validated parameters, not a shortcut around the Query Builder API.

Full-text search should use contains only when relevance-style matching is wanted. If data is genuinely unstructured, forcing every field into JCR properties makes predicates brittle. CIRCUIT’s session on MongoDB for unstructured data shows how a separate store can absorb that complexity without bloating the repository.

Tuning indexes, limits and result sets

Oak selects indexes under /oak:index by comparing query properties, node types, aggregates and cost estimates. Composite indexes can serve queries that repeatedly combine a content type, locale, status and business date. They must reflect the predicates the application actually sends, including the value formats used by the front end.

Index quality depends on consistent property values and manageable cardinality. Dates stored as incompatible strings, booleans represented inconsistently and frequently changing multivalued properties can weaken index selection. Full-text search needs its own specialised index; adding more ordinary property indexes will not remove the cost of tokenising and analysing content.

Result volume changes the economics of a query. Apply a sensible p.limit, avoid very large p.offset values and use stable ordering for pagination. Use AEM’s explain facilities, including p.explain where exposed, to inspect selected indexes, estimated costs and traversal warnings. Forcing exact hit counts or disabling result limits can turn an interactive search into an accidental bulk export.

Service-level caching can reduce repeated work, provided invalidation is dependable. Where updates arrive through background processes, the CIRCUIT material on reliable ActiveMQ messaging illustrates how message delivery can support that flow. Queues complement good index design; they do not make an inefficient predicate efficient.

Testing performance under Australian conditions

Create benchmarks from production-shaped data, not a small laboratory fixture. Include the expected content volume, multilingual paths, asset types, user permissions and concurrent search patterns. Record cold and warm cache timings, result counts, index choices and p50, p95 and p99 latency so regressions are visible rather than anecdotal.

Geography is not an edge case. An unrelated Townsville casino review makes a useful market reminder that northern Queensland users are part of the audience, not an afterthought after Sydney and Melbourne. Test experiences over the NBN connections, fixed-wireless services and mobile networks available across regional Australia rather than assuming every request resembles a metro office connection.

Operations also cross multiple time zones. Eastern states generally use UTC+10, while Adelaide runs on a half-hour offset and daylight-saving transitions affect release windows. Keep an Australian operations handover refreshingly plain: “no worries on the front end, but the Queensland query path is still timing out”. Government and enterprise buyers also expect privacy controls aligned with the Australian Privacy Act, security practices such as the ASD Essential Eight and clear answers about hosting, data residency and support arrangements.

Keeping specialised data outside JCR

JCR remains a strong fit for structured content that AEM templates and services must traverse. It is less suitable for relational reporting, transactional records, specialised search requirements or documents whose fields change independently. Keeping these concerns in the content repository can create expensive predicates and indexes for data the authoring team rarely uses.

Relational data that needs transactions, joins or aggregate reporting may belong in MariaDB. CIRCUIT’s explanation of custom persistence with MariaDB demonstrates how AEM services can use a relational store while JCR remains the content-facing layer.

Draw a clear boundary around that layer. Expose stable application services or Sling models instead of leaking database schemas into templates, define which system owns each field and account for dual-write failures, retries and cache invalidation. The external store may hold derived or operational data, but ownership must remain explicit so a query never becomes the accidental consistency mechanism for the entire platform.

A practical query review

A repeatable review should connect Java predicate construction, Oak execution and the user-visible search experience.

Before release:

  • Translate representative Query Builder trees into JCR-SQL2 and inspect the Oak plan.
  • Match selective filters to suitable indexes and consistent property types.
  • Set bounded limits, stable paging and realistic p95 latency targets.
  • Exercise concurrent searches using production-shaped content.

When performance degrades:

  • Capture the predicates, traversal warnings, query time and result cardinality.
  • Compare cold and warm caches, index selection and recent data growth.
  • Identify and roll back the change that altered query selectivity.

The review should leave behind a reproducible trace, an agreed baseline and an owner for each index or predicate decision. It should also distinguish repository changes from application, infrastructure and third-party service problems, which can otherwise be bundled into one vague performance issue.

Make the next AEM release include a query-performance gate: publish baseline traces, require an index plan for every new predicate and block regressions against agreed latency thresholds. That gives the team a measurable finish line instead of another round of hopeful tuning.