Sub topic 9
Adding Metadata and Context to Chunks
This chapter assumes you know what an embedding is, how vector similarity search works, and basic Python. It builds on the structure-aware splitter from the previous chapter.
Why a chunk needs more than its text
A chunk is retrieved alone. The model never sees the paragraph before it or the heading above it. A chunk that reads "It must be restarted after the change" is useless without knowing what "it" is.
Two tools fix this:
- Metadata is data stored next to the chunk, such as its source file, heading path, or date. It is used for filtering, citations, and display.
- Context enrichment means adding explanatory text to the chunk itself, usually before it is embedded, so the vector reflects where the text came from.
The two differ in one way. Metadata is not embedded unless you choose to embed it. Enriched text is.
Useful metadata fields
| Field | Purpose |
|---|---|
| `source` | Citation and debugging |
| `headings` | Section path, for display and enrichment |
| `chunk_index` | Fetching neighboring chunks |
| `doc_id` | Grouping chunks, deleting or re-indexing a document |
| `updated_at` | Filtering stale content |
| `access_group` | Restricting results per user |
Keep fields you will filter or display. Every extra field costs storage and must be kept current.
Worked example: heading paths
split_markdown returns sections like {"headings": ["Billing", "Refunds"], "text": "..."}. The next function turns each section into a chunk record with metadata, and builds an enriched string for embedding.
def build_records(sections, source):
records = []
for i, sec in enumerate(sections):
path = " > ".join(sec["headings"])
embed_text = f"{path}\n\n{sec['text']}" if path else sec["text"]
records.append({
"id": f"{source}#{i}",
"embed_text": embed_text,
"text": sec["text"],
"metadata": {
"source": source,
"headings": sec["headings"],
"chunk_index": i,
},
})
return records
sections = [
{"headings": ["Billing", "Refunds"], "text": "It takes five business days."},
]
for r in build_records(sections, "billing.md"):
print(r["id"])
print(r["embed_text"])The output shows the embedded text starting with Billing > Refunds. The sentence "It takes five business days" now sits next to its topic. A query about refund timing will match it more reliably.
Store text separately from embed_text. You embed the enriched version but may show the user the original, or pass either to the generator.
Other kinds of context
- Document title or summary prefix. Prepend the title to every chunk of a document.
- Generated context. Ask a language model for one or two sentences that situate each chunk within its document, and prepend them. This often improves retrieval, but it costs one model call per chunk, and the output can be wrong. Spot-check it.
- Neighbor links. Store
chunk_indexso you can fetch the chunks before and after a hit at query time. This is cheap and needs no re-embedding.
Common errors
- Enrichment pushes the chunk over the embedding limit. The prefix counts toward tokens. Measure size after adding it, or reserve room in your size budget.
- Repeating long prefixes. A 100-token title on a 150-token chunk makes every vector similar to its siblings. Keep prefixes short.
- Stale metadata. If a document is edited, re-chunk it and delete old records by
doc_id. Otherwise old and new versions both match. - Filtering on fields that were never stored. Decide your filters before you index. Adding a field later means re-indexing.
- Trusting generated context blindly. A wrong summary becomes part of the vector and misleads retrieval.
Exercise
A chunk reads "Set it to 30 seconds." Its heading path is ["API", "Timeouts", "Retry delay"]. What would you embed, what would you keep only as metadata, and why?
Show answer
Embed "API > Timeouts > Retry delay" followed by the chunk text, so the vector reflects what "it" refers to. Keep source, chunkindex, docid, and the heading list as metadata for citation, neighbor lookup, and filtering. Check that the prefixed text still fits the embedding model's token limit.