Contextual retrieval and metadata filtering
Chunking cuts a document into pieces, and each piece forgets where it came from. A chunk that says "Revenue grew 3% over the previous quarter" has lost the company name and the quarter. Two techniques restore what was lost. Contextual retrieval puts the missing context back into the text that gets embedded and indexed. Metadata filtering uses structured fields (tenant, date, document type, permissions) to narrow the search space before similarity even comes into it. Both are about making retrieval aware of facts the raw chunk text does not carry.
Why it matters
Without context, many chunks are ambiguous. Ten annual reports each contain a sentence like "Revenue grew 3%". The embedding of that sentence is nearly identical across all ten, so retrieval picks one more or less at random. Heading paths help (see the chunking doc), but they do not capture everything a reader would infer from the surrounding pages.
Metadata matters for a different reason: some constraints are hard rules, not similarity preferences. A user from tenant A must never see tenant B's chunks. A question about "the current travel policy" should not be answered from the 2019 version. These are filters, and expressing them as filters is both more reliable and more secure than hoping the embedding encodes them.
How it works
Contextual retrieval
Anthropic published this technique in 2024. For every chunk, you ask an LLM to write a short context (their write-up suggests roughly 50 to 100 tokens) that situates the chunk within the whole document, then prepend that context to the chunk before embedding it and before adding it to the BM25 index. In Anthropic's experiments, contextual embeddings reduced the top-20 retrieval failure rate by 35 percent (5.7 percent to 3.7 percent), combining contextual embeddings with contextual BM25 reduced it by 49 percent, and adding reranking brought the reduction to 67 percent.
The obvious cost objection (one LLM call per chunk, each including the whole document) is handled with prompt caching: the document is cached once and each per-chunk call only pays full price for the chunk and the instruction.
Rendering diagram…
Late chunking (from the chunking doc) solves the same problem inside the embedding model without an LLM, but it only helps the dense side. Contextual retrieval also improves keyword search, since the generated context adds the company name and period as literal terms.
Metadata filtering
Every chunk gets structured fields at ingestion: tenant_id, source_id, doc_type, language, effective_date, acl_groups, and anything else queries need to constrain. At query time you pass a filter expression to the vector database alongside the vector.
Two filter sources:
- Mandatory filters come from the authenticated request (tenant, user's groups). The application sets them; the model never touches them.
- Inferred filters come from the query ("2025", "UK", "slides only"). A model can extract these (self-query), but validate them against allowed values.
How the database applies the filter matters. Post-filtering (search then drop non-matching results) can return too few results when the filter is selective. Good engines filter during the index traversal. Qdrant builds payload indexes and filter-aware HNSW, and pgvector 0.8 added iterative index scans (hnsw.iterative_scan) so filtered queries keep scanning until enough rows match.
Reference architecture
Rendering diagram…
The order of operations encodes the security model: mandatory filters are derived from identity, inferred filters are validated, and both are applied inside the database query.
Code
Generating chunk context with the Anthropic Python SDK and prompt caching, then querying Qdrant with a tenant filter and a date range.
import os
import anthropic
from qdrant_client import QdrantClient, models
claude = anthropic.Anthropic()
MODEL = os.environ.get("CONTEXT_MODEL", "claude-haiku-4-5")
def situate_chunk(document: str, chunk: str) -> str:
msg = claude.messages.create(
model=MODEL,
max_tokens=150,
messages=[{
"role": "user",
"content": [
{
"type": "text",
"text": f"<document>\n{document}\n</document>",
"cache_control": {"type": "ephemeral"}, # reuse across chunks
},
{
"type": "text",
"text": (
f"Here is a chunk from the document:\n<chunk>\n{chunk}\n</chunk>\n"
"Write a short context that situates this chunk within the document "
"to improve search retrieval. Answer with the context only."
),
},
],
}],
)
return msg.content[0].text + "\n\n" + chunk
qdrant = QdrantClient(url="http://localhost:6333")
def search(query_vec: list[float], tenant_id: str, groups: list[str]):
flt = models.Filter(must=[
models.FieldCondition(key="tenant_id", match=models.MatchValue(value=tenant_id)),
models.FieldCondition(key="acl_groups", match=models.MatchAny(any=groups)),
models.FieldCondition(key="effective_year", range=models.Range(gte=2025)),
])
return qdrant.query_points(
collection_name="docs", query=query_vec, using="dense",
query_filter=flt, limit=20,
).points
Create payload indexes for filtered fields (qdrant.create_payload_index(...)) so filters stay fast at scale.
Trade-offs and pitfalls
- Ingestion cost and time. Contextual retrieval adds an LLM call per chunk. Prompt caching makes it affordable, but a large corpus still takes a while; run it as a batch job and cache results by chunk hash.
- Context can be wrong. A generated context that misattributes a chunk will mislead retrieval. Spot-check outputs, especially on long or multi-topic documents.
- Documents larger than the context window need a summary or section-level document input instead of the whole file.
- Re-contextualize on edits. If a document changes, its chunks' contexts may change too, even for unchanged chunks.
- Never let the model set security filters. Tenant and ACL filters come from identity, full stop. A prompt injection in a query must not be able to widen them.
- Selective filters break naive ANN. Test your most restrictive filter combination and confirm you still get k results.
- Metadata quality decays. Missing dates or wrong document types silently exclude chunks. Validate metadata at ingestion and alert on nulls.
- Too many filter fields make indexes heavy. Index the fields queries actually filter on.
Checklist
- Attach tenant, ACL, source, type, language and date metadata to every chunk.
- Derive security filters from the authenticated session and apply them inside the database query.
- Validate any model-extracted filters against allowed values.
- Index filtered fields and test the most selective filter combinations for recall.
- Prototype contextual retrieval on one collection and compare failure rates on your eval set.
- Use prompt caching for context generation and cache results by chunk hash.
- Regenerate contexts when the parent document changes.