Sub topic 9
Adding Metadata and Context to Chunks
This chapter assumes you can read basic Python and know what an embedding is. It also assumes you have seen the Markdown splitter from the structure-aware chapter, which returns sections as dictionaries with headings and text. Here you attach information to each chunk so that it still makes sense when it is retrieved alone.
The problem: a chunk has lost its surroundings
A retriever returns chunks one at a time, without the pages around them. Consider this chunk from a billing guide:
Refunds are issued within 5 business days. Contact support if the
payment does not appear after that time.Which product does this describe? Which version of the guide is it from? Is it about card payments or bank transfers? The chunk does not say. The answer may sit in a heading three levels up, or in the file name, or on a page the splitter cut away.
Missing context hurts in three places:
- Embedding. The vector for the chunk only encodes what the text says. A query like "Billing API refund timing" may score lower than it should, because "Billing API" never appears in the chunk.
- Filtering. Without fields such as product or language, you cannot restrict search to the right subset of the corpus.
- Generation and citation. The model cannot tell the user where an answer came from, and it may mix up text from different versions of a document.
The fix is to store two kinds of extra information with every chunk: metadata (structured fields kept next to the text) and context (words added to the text that gets embedded).
Metadata versus context text
These two are easy to confuse, but they do different jobs.
| Row | Metadata fields | Context text |
|---|---|---|
| Form | Key-value pairs stored beside the vector | Words prepended to the chunk before embedding |
| Affects the vector | No | Yes |
| Used for | Filtering, citations, deduplication, debugging | Making the vector reflect where the chunk sits |
| Cost | Storage only | Uses embedding input tokens |
| Example | `{"source": "docs/billing.md", "version": "v2"}` | `Billing API > Refunds` |
A good record keeps both. The vector is computed from the context-prefixed text, and the stored text field stays as the original passage, so the user sees clean content.
Choosing metadata fields
Add a field only if you will use it for filtering, display, or updating the index. Common choices:
| Field | Purpose |
|---|---|
| `doc_id` | Groups chunks from the same document; lets you delete or re-index a whole document |
| `source` | A path or URL, used for citations |
| `headings` | The heading path, such as `["Billing API", "Refunds"]` |
| `position` | Order of the chunk in the document, used to rebuild neighbors |
| `prev_id`, `next_id` | Links to adjacent chunks, so you can fetch surrounding text at answer time |
| `updated` | Last modified date, for freshness filters and stale-data cleanup |
| `version`, `language`, `doc_type` | Filters that match how users scope their questions |
| `access` | Who may see the chunk (see the warning below) |
Chunk ids deserve attention. If you derive the id from the document id, position, and text, then an edited chunk gets a new id. You can then compare old and new ids to find which chunks to re-embed, and leave the rest alone.
Building chunk records
This function takes sections shaped like the output of split_markdown. It produces one record per section, with metadata, neighbor links, and a context-prefixed embed_text.
import hashlib
def build_records(sections, doc_id, source, updated="2026-11-01"):
records = []
for i, sec in enumerate(sections):
headings = sec["headings"]
text = sec["text"]
prefix = " > ".join([doc_id] + headings)
digest = hashlib.sha1(f"{doc_id}:{i}:{text}".encode("utf-8"))
records.append({
"id": digest.hexdigest()[:12],
"doc_id": doc_id,
"source": source,
"headings": headings,
"position": i,
"updated": updated,
"text": text,
"embed_text": f"{prefix}\n{text}",
"prev_id": None,
"next_id": None,
})
for a, b in zip(records, records[1:]):
a["next_id"] = b["id"]
b["prev_id"] = a["id"]
return records
def filter_records(records, **conditions):
return [
r for r in records
if all(r.get(key) == value for key, value in conditions.items())
]
sections = [
{"headings": ["Billing API", "Refunds"],
"text": "Refunds are issued within 5 business days."},
{"headings": ["Billing API", "Invoices"],
"text": "Invoices are generated on the first of each month."},
]
records = build_records(sections, doc_id="billing-guide", source="docs/billing.md")
print(records[0]["embed_text"])
print(records[0]["next_id"] == records[1]["id"])
print(len(filter_records(records, doc_id="billing-guide")))Running it prints:
billing-guide > Billing API > Refunds
Refunds are issued within 5 business days.
True
2Pass record["embed_text"] to your embedding model. Store record["text"] and the other fields as the payload next to the vector. Most vector databases accept a payload of this kind and let you filter on it at query time.
How the pieces flow through the pipeline
Using metadata at query time
Filtering
A user asking about version 2 of an API should not get version 1 chunks, however similar the text is. Apply a filter on version alongside the vector search. Two implementation styles exist:
- Pre-filtering restricts the candidate set before the similarity search. Results are always the top k matches within the allowed subset.
- Post-filtering takes the top k by similarity and then drops the ones that fail the filter. This can return fewer than k results, or none, when the filter is selective.
Check which style your vector store uses. If it post-filters, retrieve a larger k and trim afterwards.
Neighbor expansion
When a retrieved chunk begins or ends mid-thought, use prev_id and next_id to fetch the adjacent chunks and give the model a wider window. This is a light version of the idea you will see fully developed in the parent-child chapter.
Citations
Put the source and heading path into the prompt next to each chunk. The model can then cite them, and a reader can check the claim.
def format_context(retrieved):
blocks = []
for n, r in enumerate(retrieved, start=1):
where = " > ".join(r["headings"])
blocks.append(f"[{n}] {r['source']} ({where})\n{r['text']}")
return "\n\n".join(blocks)Calling format_context(records) on the two records above produces numbered blocks such as [1] docs/billing.md (Billing API > Refunds) followed by the passage.
Edge cases and pitfalls
Context text counts against the embedding limit
The prefix is part of the input, so a long heading path eats tokens that the chunk body could have used. If your chunk size is set right up to the embedding model's limit, adding a prefix can cause silent truncation of the end of the chunk. Reserve room: measure the prefix in tokens and subtract it from your chunk budget.
Keep volatile fields out of the embedded text
Dates, version numbers, and ids change often, and they add noise to the vector. Put them in metadata fields only. Embed the stable, meaningful parts: document title, heading path, and perhaps the section's topic.
Do not let the prefix dominate
If every chunk in a 200-chunk document starts with the same long title, the shared words pull all those vectors toward each other. Search then has a harder time telling the chunks apart. Keep the prefix short, usually the document title and the last two or three headings.
Heading paths can be wrong
The split_markdown function matches any line starting with #. Inside a fenced code block, a comment such as # install dependencies is read as a heading. This corrupts the heading path for everything after it. Track whether you are inside a fence, and ignore # lines while you are.
Tables and code need their own context
A table row such as | 5 | 30 days | means nothing alone. When you split a large table, repeat the header row in every chunk. For code, include the file name and the enclosing function or class name in the prefix.
Metadata goes stale
If a document is updated and you re-embed only some chunks, the index mixes old and new records. Use doc_id to delete all old chunks for a document before inserting the new ones, or compare ids as described earlier.
Metadata is not an access control system by itself
An access field only protects data if the filter is enforced on the server side, using the identity of the caller, for every query. Do not let user-supplied text or the model decide the filter. Also remember that the context text sits inside the chunk, so confidential titles in a prefix end up in prompts.
Generated context is optional and costly
Some systems ask a language model to write a one-sentence summary of where each chunk fits in its document, then prepend that sentence before embedding. It can help with documents whose headings are weak. It also costs one model call per chunk and must be redone when the document changes. Try the free options first: headings, titles, and file names.
Summary of decisions
- Store metadata in fields for anything you filter, cite, or use for updates.
- Prepend a short context prefix to the embedded text so the vector reflects the chunk's place in the document.
- Keep the original text separately for display and prompts.
- Budget tokens for the prefix, and keep volatile values out of it.
- Link neighbors so you can widen the context after retrieval.
Exercise
A chunk of 480 tokens is embedded with a model whose input limit is 512 tokens. You add the prefix "employee-handbook > Benefits > Parental leave > Eligibility" to each chunk, which is 18 tokens, and a "last updated: 2026-11-01" line, which is 9 tokens. What goes wrong, and how would you fix it?
Show answer
The input is now 480 + 18 + 9 = 507 tokens, which still fits, but any chunk above 485 tokens would be truncated and lose its ending without an error. Fix it by lowering the chunk size so that chunk tokens plus prefix tokens stay under 512, and by removing the date line from the embedded text. The date should live only in the updated metadata field, where it can be used for filtering and does not add noise to the vector.
Exercise
Your vector store post-filters results. You search with k=5 and a filter version == "v2", but only 1 of the top 5 chunks is from v2. What happens, and what can you do?
Show answer
You get one result instead of five, because the other four are discarded after retrieval. You can request a larger k (for example 30) and keep the first five that pass the filter, or switch to a store or query mode that pre-filters before the similarity search.