The short answer#
A useful retrieval-augmented generation (RAG) chunk keeps an answer-bearing passage together and carries enough metadata to trace it to its source. Separate the text used for matching from the source identity, section and version returned with it. Choose boundaries by checking real questions, complete supporting passages and resolvable citations, rather than a universal chunk size.
Start with the condition your answer must preserve#
Imagine a fictional equipment guide containing this section:
A replacement laptop may be requested. A repair assessment must first confirm that repair is impractical.
The reader asks, “Can I request a replacement laptop?” A chunk containing only the first sentence looks relevant. It also leaves out the condition that changes the answer.
Putting a source label beside that sentence would help someone find it. It would not restore the missing condition. You need both a usable passage and a route back to the original.
Here, a chunk means a unit stored for retrieval. Provenance means the information that traces that unit back to its origin. The design question is what must travel together when the retriever selects one unit.
If you are new to the overall flow, start with how RAG uses retrieved evidence. This exercise focuses on the representation of that evidence.
Keep three responsibilities visible#
An embedding is a numerical representation used for matching. It does not replace the source text or its identity. Microsoft's vector-search overview explains the matching step; the following separation is an application design choice.
| Part | What this example stores | What it is for |
|---|---|---|
| Matching text | Document title, section heading and passage | Give the retriever context for the passage |
| Evidence text | The original section body | Supply the wording the answer must respect |
| Provenance | Document ID, revision, section ID and heading | Resolve and display the selected source |
Keep technical identifiers as metadata rather than expecting their presence in embedding text to perform a lookup. When a result comes back, return its provenance with the evidence. In a real index, check that your query actually selects those fields.
This is compatible with a chunk-oriented index: Microsoft's index-projection example keeps parent identifiers and titles alongside child chunks. Our field names below are illustrative, not a required vendor schema.
Run a small representation check in TypeScript#
This example starts after document parsing. Its input is two already extracted sections of a fictional guide. It calls no model and generates no answer.
In a scratch Node.js project, install the TypeScript runner with npm install --save-dev tsx. Save the following as chunk-demo.ts, then run npx tsx chunk-demo.ts.
import assert from "node:assert/strict";
type Section = { id: string; heading: string; body: string };
type Chunk = {
id: string;
body: string;
matchingText: string;
source: {
documentId: string;
revision: string;
sectionId: string;
title: string;
heading: string;
};
};
// Fictional teaching data. A revision is an identity label, not a date.
const documentId = "equipment-guide";
const revision = "r1";
const title = "Equipment guide";
const sections: Section[] = [
{
id: "replacement",
heading: "Laptop replacement",
body: "A replacement laptop may be requested. " +
"A repair assessment must first confirm that repair is impractical.",
},
{
id: "returns",
heading: "Equipment returns",
body: "Return equipment through the service desk when leaving a team.",
},
];
const chunks: Chunk[] = sections.map(section => ({
id: `${documentId}/${revision}/${section.id}`,
body: section.body,
matchingText: `${title}\n${section.heading}\n${section.body}`,
source: {
documentId, revision, sectionId: section.id,
title, heading: section.heading,
},
}));
const words = (text: string) =>
new Set(text.toLowerCase().match(/[a-z]+/g) ?? []);
function retrieve(query: string, candidates: Chunk[]) {
const terms = words(query);
return candidates.map(chunk => ({
chunk,
score: [...words(chunk.matchingText)]
.filter(word => terms.has(word)).length,
})).filter(hit => hit.score > 0)
.sort((a, b) => b.score - a.score ||
a.chunk.id.localeCompare(b.chunk.id));
}
// This map stands in for an application-owned source resolver.
const originals = new Map(chunks.map(chunk => [chunk.id, chunk.body]));
const complete = chunks[0]!;
const firstSentence = complete.body.split(". ")[0]! + ".";
const broken: Chunk = {
...complete,
body: firstSentence,
matchingText: `${title}\n${complete.source.heading}\n${firstSentence}`,
};
const query = "replacement laptop";
const brokenHit = retrieve(query, [broken])[0]!.chunk;
const hit = retrieve(query, chunks)[0]!.chunk;
assert.equal(brokenHit.body.includes("repair assessment"), false);
assert.notEqual(originals.get(brokenHit.id), brokenHit.body);
assert.equal(hit.body.includes("repair assessment"), true);
assert.equal(originals.get(hit.id), hit.body);
assert.equal(retrieve("catering", chunks).length, 0);
console.log("Broken passage keeps condition:",
brokenHit.body.includes("repair assessment"));
console.log("Broken citation resolves to exact passage:",
originals.get(brokenHit.id) === brokenHit.body);
console.log("Complete passage keeps condition:",
hit.body.includes("repair assessment"));
console.log("Citation resolves to exact passage:",
originals.get(hit.id) === hit.body);
console.log(JSON.stringify({
evidence: hit.body,
citation: { sourceKey: hit.id, ...hit.source },
}, null, 2));
The first four output lines are:
Broken passage keeps condition: false
Broken citation resolves to exact passage: false
Complete passage keeps condition: true
Citation resolves to exact passage: true
The broken passage deliberately retains the complete passage's key: it still opens a source, but that source is not the exact passage returned. The added mismatch assertion exposes this second failure. The successful result's JSON includes the full rule and its condition, plus the source key equipment-guide/r1/replacement. Application code creates that citation payload from the selected result.
The selector counts shared words. It cannot recognise paraphrases or decide answerability. The substring checks target this tiny fixture; they are not a general test of claim support. The in-memory map proves only that this example resolves its own stored passage; a deployed resolver needs to open the corresponding retained source version.
If a long section needs several passages, keep the section as the parent and add a passage location. For example, the first passage could carry:
{
"sourceKey": "equipment-guide/r1/replacement#p1",
"sectionId": "replacement",
"passage": 1
}
The resolver must retain that exact passage under that key. The ordinal identifies a location within this extraction, not a location that will stay fixed after rechunking; changed boundaries need a new revision or extraction identity.
Choose boundaries by what the reader needs to know#
The example keeps one short section per chunk. That is useful here because the section expresses one rule and its condition. It would be unsuitable for a section containing several unrelated procedures or exceeding your embedding model's input limit.
Microsoft's chunking guidance describes using document structure and overlap. Treat a size setting as an experiment. A heading helps locate a topic; it does not guarantee that the passage beneath it is complete.
Your evidence budget is the amount of retrieved text you allow into one model call. Compare boundaries within the same budget so that larger passages do not receive an unexamined advantage.
| Approach | Useful starting point | Failure to inspect |
|---|---|---|
| One complete short section | A rule and its conditions sit together | An oversized section contains several answers |
| Smaller passages with heading context | Long sections need finer retrieval | A condition or definition lies outside the passage |
| Overlapping passages | Relevant text crosses a boundary | Near-duplicate results consume the evidence budget |
| A small match expanded to surrounding text | The match identifies a location within a larger explanation | Expansion brings irrelevant or unauthorised text |
Azure Databricks' pipeline guidance describes the size trade-off: focused passages can lose context, while broader ones can carry distracting material. Use your questions to decide which failure matters.
For tables, preserve the relevant row and its column labels. For procedures, inspect whether prerequisites survive. For rules, look for exceptions and conditions even when they sit under another heading. If parsing has lost that structure, fix extraction before tuning retrieval.
Keep citation identity separate from answer support#
In this fixture, a document ID, revision and section ID form the source key. It is repeatable for the same input. If the text or extraction boundaries change, update the revision or extraction identity too; silently reusing the key would make old evidence ambiguous.
For a PDF, a resolver might need a retained file revision, page and passage location. For a web page, it might need a stored snapshot and anchor. A mutable URL alone cannot show exactly which wording an earlier answer used. These are design requirements to implement and test, not properties created by adding a revision string.
Keep two checks separate:
- Source resolution: does the returned identifier open the correct source version and location?
- Claim support: does that passage actually support the answer, including its conditions?
A correct link can accompany an unsupported answer. A complete passage can accompany a broken link. Similarity ranking resolves neither question on its own.
What this means for you#
Before changing models, take a small set of representative questions and inspect the evidence your pipeline actually returns. Include questions about a condition, a table, a cross-section explanation and something the corpus cannot answer.
For each question, record the expected supporting passage, the returned passage, any missing qualification and whether its citation resolves. Compare boundary choices using the same questions and evidence budget. If overlap returns several copies of the same rule, count the duplicated context too.
When adapting the exercise to vector or hybrid retrieval, evaluate ranking and insufficient-evidence behaviour separately. Keep the evidence and provenance fields intact as you replace the selector.
For architects, record who owns retention of source versions and which component resolves each source key to the retained passage.
This representation exercise also does not implement access control or freshness. A revision label cannot establish that evidence is current, and a document ID cannot authorise a reader. Apply those controls before evidence reaches the model, including any surrounding text fetched during expansion.
Questions developers ask#
Should every chunk contain all the document metadata?#
Carry what the retrieval, filtering and source-resolution paths need. A short title may help matching; a source key belongs in the result metadata. Avoid copying unrelated document fields into every prompt. Inspect the returned payload rather than assuming the index includes them.
When should I avoid chunking?#
When a small, coherent document can be retrieved as a whole and fits the intended input budget, splitting it may add no useful precision. When the question requires a current system value or a calculation, consider a direct query or deterministic operation instead of trying to recover it from prose.
How can a team practise this as an architecture decision?#
Compare candidate pipelines against the same questions and record why one preserves the necessary evidence better. Session 1 of GenAI Design & Architecture — Engineering Robust Enterprise AI Systems develops retrieval design through a lab examining relevance, provenance, permissions, latency and failure behaviour.
Enquire about the workshop to practise these choices with your team.
