Skip to content
AgenticAIWiki
  1. Learn
  2. Part 1
  3. 4. Embeddings and semantic search
  4. 4.6

Lesson 4.6 · 6 of 10 · 5 min read · Reviewed 24 Nov 2026

Chunk, document and query embeddings

By the end, you can

  • Decide what unit of text to embed.
  • Handle queries and documents differently when it helps.

The unit you embed decides what you can find

One vector summarises everything you put into it. Put in a whole manual and the vector means “this is roughly about printers”. Put in one paragraph and it means “how to clear a paper jam in tray 2”.

Unit Good for Weak at
Whole document “Which documents are about X?”, clustering, dedup Finding a specific fact
Chunk (a few hundred tokens) Precise RAG retrieval Losing context from the rest of the document
Sentence Very precise matching, highlighting Too little context; huge index
Summary of a document Coarse routing Misses details not in the summary

A two-level pattern

1. Document vectors   --> pick the 20 most relevant documents
2. Chunk vectors      --> within those, pick the 5 best chunks
3. Claude             --> answer from the 5 chunks, citing them

This keeps the chunkChunking: Splitting documents into smaller passages before embedding and indexing them. search small and stops one huge document from swamping the results.

Chunks lose their context

A chunk that says “It must be returned within 30 days” doesn’t say what it is. Two fixes:

  • Prefix with a title or path: Returns policy > Laptops: It must be returned within 30 days.
  • Contextual chunking: ask a model to write one sentence placing the chunk in its document, and embed that sentence plus the chunk. Anthropic’s Contextual RetrievalContextual retrieval: Adding a short, document-aware context sentence to each chunk before embedding and indexing it. write-up reports large drops in failed retrievals with this approach (23.x covers it in depth).

Chunk sizes and overlap are covered in 48.1. The point here is that what goes into the vector is a design choice, not just a split.

Queries are different from documents

A query is often 5 words; a chunk is 300. Some embedding modelsEmbedding model: A model trained to turn text (or images) into embeddings for search and comparison, rather than to generate text. handle this by asking you to mark which is which, using an input type flag or a prefix such as query: and passage:. If your model supports it, use it on both sides; getting it wrong quietly lowers quality.

Other tricks for short queries:

  • Rewrite the query into a fuller question before embeddingEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together. it.
  • Embed a hypothetical answer (write a short fake answer, embed that, search with it). This sometimes matches documents better than the bare question.

Averaging vectors

You can make a document vector by averaging its chunk vectors. It’s cheap, and fine as a rough filter. But an average of “billing”, “shipping” and “login” chunks lands in the middle of nowhere, so never use it for precise matching.

Key points

  • You can embed whole documents, chunks, or both. Chunks give precise matches; document vectors give a coarse first filter.
  • A chunk embedded without its context loses meaning; adding a short context line or title helps retrieval.
  • Queries are short and documents long, so some models use separate query and document modes.
  • Averaging many chunk vectors into one document vector blurs it; it works as a rough filter, not a precise match.
Hands-on labRuns in the Playground

Prefix chunks with their section heading

Show that a chunk embedded without context can't be found, and fix it with a heading prefix.

You will have: A before-and-after retrieval result for the query 'laptop return window' with bare and prefixed chunks.

Steps

  1. Run the starter: the bare chunk 'It must be returned within 30 days' doesn't mention laptops.
  2. Note which chunk the query retrieves first without prefixes.
  3. Fill in with_prefix(): put the heading path in front of each chunk's text before embedding.
  4. Run again and confirm the laptop returns chunk now ranks first.
  5. Try a second query, 'parcel return window', and check it picks the other chunk.

Done when

  • Without prefixes the laptop query ranks the specs chunk 'laptops-2' first.
  • With prefixes 'laptops-1' ranks first for the laptop query.
  • The parcel query picks 'parcels-1'.

Open in the Playground No API key needed.

Starter code (Python)
import math
WORDS = {"laptop": [1, 0, 0], "laptops": [1, 0, 0], "parcel": [0, 1, 0], "parcels": [0, 1, 0],
         "return": [0, 0, 0.5], "returned": [0, 0, 0.5], "returns": [0, 0, 0.5]}
CHUNKS = [
    {"id": "laptops-1", "path": "Returns policy > Laptops", "text": "It must be returned within 30 days."},
    {"id": "parcels-1", "path": "Returns policy > Parcels", "text": "Unopened parcels are returned within 14 days."},
    {"id": "laptops-2", "path": "Laptops > Specs", "text": "Laptops ship with a 65 W charger."},
]

def embed(t):
    v = [0.0, 0.0, 0.0]
    for w in t.lower().replace(">", " ").replace(".", " ").split():
        for i, x in enumerate(WORDS.get(w, [0, 0, 0])):
            v[i] += x
    return v

def cosine(a, b):
    d = sum(x * y for x, y in zip(a, b)); la = math.sqrt(sum(x * x for x in a)); lb = math.sqrt(sum(x * x for x in b))
    return d / (la * lb) if la and lb else 0.0

def with_prefix(chunk):
    return chunk["text"]  # TODO: return the heading path, a colon, then the text

def search(q, prefixed):
    qv = embed(q)
    texts = {c["id"]: (with_prefix(c) if prefixed else c["text"]) for c in CHUNKS}
    return sorted(texts, key=lambda i: (-cosine(qv, embed(texts[i])), i))

for q in ["laptop return window", "parcel return window"]:
    print(q, "| bare:", search(q, False)[0], "| prefixed:", search(q, True)[0])
Show a solution
import math
WORDS = {"laptop": [1, 0, 0], "laptops": [1, 0, 0], "parcel": [0, 1, 0], "parcels": [0, 1, 0],
         "return": [0, 0, 0.5], "returned": [0, 0, 0.5], "returns": [0, 0, 0.5]}
CHUNKS = [
    {"id": "laptops-1", "path": "Returns policy > Laptops", "text": "It must be returned within 30 days."},
    {"id": "parcels-1", "path": "Returns policy > Parcels", "text": "Unopened parcels are returned within 14 days."},
    {"id": "laptops-2", "path": "Laptops > Specs", "text": "Laptops ship with a 65 W charger."},
]

def embed(t):
    v = [0.0, 0.0, 0.0]
    for w in t.lower().replace(">", " ").replace(".", " ").replace(":", " ").split():
        for i, x in enumerate(WORDS.get(w, [0, 0, 0])):
            v[i] += x
    return v

def cosine(a, b):
    d = sum(x * y for x, y in zip(a, b)); la = math.sqrt(sum(x * x for x in a)); lb = math.sqrt(sum(x * x for x in b))
    return d / (la * lb) if la and lb else 0.0

def with_prefix(chunk):
    return f"{chunk['path']}: {chunk['text']}"

def search(q, prefixed):
    qv = embed(q)
    texts = {c["id"]: (with_prefix(c) if prefixed else c["text"]) for c in CHUNKS}
    return sorted(texts, key=lambda i: (-cosine(qv, embed(texts[i])), i))

for q in ["laptop return window", "parcel return window"]:
    print(f"{q} | bare: {search(q, False)[0]} | prefixed: {search(q, True)[0]}")
Quick checkA 40-page policy is embedded as one vector, and specific questions rarely find it. What's the best first fix?
How sure are you?
Pick an answer and how sure you are