SEARCH & AI / 010

Chunking AEM Content for RAG

A practical exploration of splitting structured AEM content for retrieval while preserving component context, citations and update boundaries.

SHARE
LinkedIn X Facebook Threads

Topic map

Engineering path

Chunking AEM Content Fragments for RAG

  1. 01Model
  2. 02Fields
  3. 03Boundaries
  4. 04Context
  5. 05Evidence

SYSTEM OVERVIEW

SYSTEM / FLOW

One source. Three boundary strategies.

Alternative experiments on the same normalized fragment—not three pipelines that must run in production. Compare their evidence before selecting a strategy. All retain source revision, locale and access scope.

A / WHOLE FRAGMENTTitle + allfieldsOne retrievalunitComplete contextB / FIELD-AWAREModel + field IDsSections /paragraphsParent contextC / SEMANTICOrdered passagesTopic boundariesVersionedsegmentsCOMBINED PATHCandidate chunksMetadata contractToken-budgetcheckRetrievalevaluation

A / Whole fragment

  1. Title + all fields
  2. One retrieval unit
  3. Complete context

B / Field-aware

  1. Model + field IDs
  2. Sections / paragraphs
  3. Parent context

C / Semantic

  1. Ordered passages
  2. Topic boundaries
  3. Versioned segments

Combined path

  1. Candidate chunks
  2. Metadata contract
  3. Token-budget check
  4. Retrieval evaluation

THIS ARTICLE EXPLORES

  1. How a fragment's model becomes a useful retrieval boundary.
  2. What whole-fragment, field-aware and semantic chunking preserve or lose.
  3. How to reproduce the same chunk set from the same revision.
  4. What an edit, deletion or permission change means for indexed chunks.
  5. How to compare strategies without inventing an accuracy score.

01 / PROBLEM

A shorter passage is not automatically better evidence.

A chunk can match a question while omitting the condition that makes its answer correct. Splitting a procedure between its precondition and action is a retrieval failure even when both pieces are indexed successfully.

This note explores boundary choices using an explicitly fictional fixture and a small executable JavaScript example. It is not a deployed AEM connector, a benchmark or a claim of production RAG ownership.

02 / AEM CONTENT SOURCE

Preserve structure before splitting text.

AEM Content Fragment Models provide named fields and references. Keep those boundaries during extraction instead of immediately flattening a fragment into one string. Select retrieval fields explicitly; author notes, internal identifiers and referenced content do not all belong in the embedding payload.

The fixture below is the application's normalized input, not an Adobe GraphQL response. Stable section IDs must be provided by your normalization contract. Resolve rich text, references and locale variants before this example runs; do not strip markup with a broad regular expression.

Fictional normalized fragment

JSON / illustrative input
{
  "sourceId": "guide-example",
  "locale": "en",
  "contentVersion": "revision-1",
  "publicationState": "published",
  "accessScope": [
    "example-readers"
  ],
  "title": "Example service access guide",
  "sections": [
    {
      "id": "request",
      "heading": "Request access",
      "text": "Ask the service owner to approve the request.\n\nRecord the approval before provisioning access."
    },
    {
      "id": "withdraw",
      "heading": "Withdraw access",
      "text": "Remove access when the approved scope no longer applies."
    }
  ]
}

Model-aware preparation

Resolve references only within the permitted source scope and keep citation targets attached to the result.

  1. 01Select model fields
  2. 02Resolve allowed references
  3. 03Normalize rich text
  4. 04Retain section IDs
  5. 05Choose boundaries

03 / CHUNKING

Compare three ways of carrying the same meaning.

Whole-fragment retrieval is a useful baseline for short, coherent content. Field-aware splitting uses the structure authors already maintain. Semantic segmentation tries to infer topic changes, which adds another transformation to evaluate and version.

Do not confuse sentence-based splitting with semantic topic detection. If the storage product chunks text automatically, inspect its actual settings and output rather than assuming they match the boundaries defined in your application.

Boundary choices for the access-guide fixture

Whole fragment

[ title + request + withdraw ]

  • Context: both procedures remain together.
  • Retrieval: one candidate can contain unrelated instructions.
  • Updates: any edit replaces the complete unit.
  • Complexity: low, until document/token size grows.

Field-aware

[ title + request §1 ] [ title + request §2 ] [ title + withdraw ]

  • Context: repeat the title and heading in each unit.
  • Retrieval: narrower candidates may need adjacent evidence.
  • Updates: paragraph insertion can shift ordinal identities.
  • Complexity: explicit model mapping and reconciliation.

Semantic

[ approval topic ] [ provisioning topic ] [ withdrawal topic ]

  • Context: inferred boundaries can cross authored fields.
  • Retrieval: test whether segmentation separates required conditions.
  • Updates: a small edit may change several boundaries.
  • Complexity: segmentation settings/model and output must be versioned.

04 / IMPLEMENTATION

Make the baseline reproducible before making it clever.

This field-aware baseline splits normalized paragraphs and carries the title, section heading and provenance into each result. Its IDs include source, locale, strategy and section, so equivalent input produces equivalent identities. It intentionally uses no embedding or inference service.

This is a teaching implementation for validated input. It does not parse HTML, enforce user authorization, count model tokens, handle tables or pack adjacent paragraphs. In a real ingestion service, add those policies explicitly rather than silently treating this function as production-ready.

Deterministic paragraph baseline

JavaScript / no dependencies
function chunkFragment(fragment) {
  // Input is an already validated, normalized application document.
  // Publication and scope values must come from a trusted source.
  if (fragment.publicationState !== "published") return [];
  const sectionIds = fragment.sections.map(section => section.id);
  if (new Set(sectionIds).size !== sectionIds.length) {
    throw new Error("Section IDs must be unique");
  }
  return fragment.sections.flatMap(section => {
    const paragraphs = section.text.replace(/\r\n?/g, "\n")
      .split(/\n\s*\n/).map(text => text.trim()).filter(Boolean);
    return paragraphs.map((body, ordinal) => ({
      chunkId: [fragment.sourceId, fragment.locale, "field-v1",
        section.id, ordinal].map(encodeURIComponent).join(":"),
      sourceId: fragment.sourceId,
      locale: fragment.locale,
      contentVersion: fragment.contentVersion,
      accessScope: [...fragment.accessScope],
      field: section.id,
      ordinal,
      text: [fragment.title, section.heading, body].join("\n")
    }));
  });
}
Expected result for the fixture
Chunk identityInherited contextPassage
guide-example:en:field-v1:request:0Example service access guide / Request accessAsk the service owner to approve the request.
guide-example:en:field-v1:request:1Example service access guide / Request accessRecord the approval before provisioning access.
guide-example:en:field-v1:withdraw:0Example service access guide / Withdraw accessRemove access when the approved scope no longer applies.

05 / METADATA

Keep chunk identity separate from source revision.

A stable chunk key identifies the logical storage slot; contentVersion identifies the source revision. Replaying a revision should be idempotent. Reusing a slot for new text still requires replacing its embedding and any cached result derived from it.

The example uses paragraph ordinals. Insert a paragraph near the beginning and subsequent keys refer to different text. Do not update only the new ordinal: replace the source's complete chunk set, or use a more sophisticated identity scheme with equally explicit deletion behavior.

EXAMPLE SCHEMA / NOT AN AEM CONTRACT

Fields that must survive splitting

This envelope describes the example application's contract. It is not an automatically enforced AEM policy.

chunkId
"guide-example:en:field-v1:request:0"Logical slot with a versioned boundary strategy.
contentVersion
"revision-1"Revision whose text generated this chunk and embedding.
locale
"en"Keep translations independently addressable.
accessScope
["example-readers"]Trusted policy metadata; not authorization by itself.
field / ordinal
"request" / 0Locate the passage within this normalization strategy.

06 / CONTEXT BUDGET

Budget context without hiding information loss.

Count tokens using the selected model's tokenizer after adding headings and any repeated context. A word count is not a portable token budget, especially across languages. A single oversized paragraph needs an explicit secondary split rule or rejection path; never silently truncate it.

Overlap can retain boundary context but also introduces repeated evidence. When combining retrieved chunks, deduplicate shared text where appropriate and keep citations tied to the actual source passages. Retrieval top-k is not the same as the final prompt's evidence budget.

Two different size checks

Document embedding and generation can have different model limits. Validate both contracts.

  1. 01Chunk + headings
  2. 02Embedding token budget
  3. 03Retrieve candidates
  4. 04Authorized expansion
  5. 05Generation context budget

07 / INGESTION

A new chunk set must retire the old one.

Create a manifest of the desired chunk IDs for a source revision. Write and validate the new set, then remove records that no longer belong. The exact atomic cutover mechanism depends on the store; where needed, use generation markers so queries cannot mix a half-written revision with its predecessor.

Serialize or compare-and-set competing revisions so a delayed retry cannot overwrite a newer source. Treat an unpublished/deleted source as an instruction to reconcile to an empty set, not as a reason to skip cleanup.

Source-level replacement

A proposed lifecycle to validate against the chosen search store, not a transaction guarantee.

  1. 01Read current revision
  2. 02Build chunk manifest
  3. 03Write replacement set
  4. 04Validate completeness
  5. 05Switch visible revision
  6. 06Retire obsolete records
Mutation cases
ChangeRiskRequired check
Insert first paragraphOrdinal IDs shift; old text can remain in reused slots.Every returned slot matches the new revision.
Shorten a sectionTrailing chunks survive a partial upsert.Old IDs absent from the new manifest are removed.
Update titleInherited context changes in every chunk.All affected embedding text is regenerated.
Change access scopeUnchanged text retains stale access metadata.Policy projection and answer caches are invalidated.
Unpublish / deleteA retry resurrects withdrawn content.No record remains visible; stale writes are rejected.

08 / PERMISSIONS

Splitting content must not widen access.

When expanding a chunk to its parent or neighbors, authorize every added passage. A model reference is not permission to merge content. Keep restricted fragments separate unless the policy decision explicitly permits their combined use.

The example copies accessScope from trusted normalized input. It does not authenticate a caller or evaluate policy. Enforce authorization in retrieval and before any external reranker or LLM receives text; fail closed if the required policy is missing.

SYSTEM / FLOW

Authorize expansion, not just the first hit

The rejected branch terminates without entering the model context.

ALLOWED EVIDENCERetrieved chunkParent /neighborsScope recheckBudgeted contextREJECTED EVIDENCERestrictedneighborScope check failsExclude fromcontext

Allowed evidence

  1. Retrieved chunk
  2. Parent / neighbors
  3. Scope recheck
  4. Budgeted context

Rejected evidence

  1. Restricted neighbor
  2. Scope check fails
  3. Exclude from context

09 / EVALUATION

Test boundaries with questions that can expose them.

Use the same corpus revision and reviewed questions for each strategy. Inspect the retrieved passages before evaluating generated answers: a correct answer produced from missing evidence does not validate retrieval.

The cases below are proposed tests, not measured performance claims. For the fictional fixture, the procedural question should retrieve both approval and provisioning context; a withdrawal question should not be dominated by repeated request chunks.

Boundary evaluation worksheet
Question / mutationEvidence to inspectFailure signal
What happens before provisioning?Approval and recording conditions survive in the selected evidence.Only the provisioning phrase is retrieved.
When should access be removed?Withdrawal section ranks as a relevant passage.Repeated request chunks crowd it out.
Replay the same inputChunk IDs and text are byte-for-byte repeatable.Duplicate or unstable identities.
Translate the fragmentLocale remains part of identity and retrieval filters.One language overwrites another.
Empty / oversized sectionEmpty sections produce no records; oversized input follows an explicit policy.Empty vectors or silent truncation.
Insert, shorten, unpublishIndex matches the new source manifest or an empty set.Superseded passages remain retrievable.

10 / FAILURE MODES

Make a bad boundary diagnosable.

Log the source revision, strategy version, chunk IDs and stage status without dumping sensitive text. These identifiers let you distinguish a segmentation problem from stale indexing, retrieval ranking or generation behavior.

Failure → evidence → mitigation
FailureDetectionMitigation
Orphaned pronoun or conditionReview the passage without its parent; meaning is ambiguous.Carry the heading; group dependent passages or expand with authorization.
Split table or procedureResult lacks a header, prerequisite or ordered step.Add structure-aware normalization before text splitting.
Duplicate evidenceNear-identical passages dominate candidate results.Bound overlap and inspect deduplication/diversity behavior.
Unstable semantic boundariesSame revision yields different segment sets.Version segmentation settings and retain reproducible output.
Stale embedding in reused slotChunk text/revision and vector provenance disagree.Regenerate and reconcile the affected source set.

11 / TRADEOFFS

Choose the simplest strategy that preserves the answer.

Start with whole-fragment and field-aware baselines. Add semantic segmentation when a reviewed question set demonstrates a boundary problem that simpler rules do not resolve. Keep the strategy replaceable and evaluate its operational cost as well as retrieval behavior.

This remains a bounded engineering exploration. The executable example demonstrates deterministic splitting only; it does not establish relevance gains, end-to-end authorization or production readiness. Continue with the linked metadata and retrieval notes for the surrounding system boundaries.

Before promoting a chunking strategy

  • Inspect real model structures, references, languages and long fields.
  • Review dependent passages and citations with the content owner.
  • Measure token budgets with the actual embedding and generation models.
  • Rehearse retries, revision replacement, withdrawal and permission changes.
  • Compare strategies on the same labeled questions before claiming improvement.

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