Chunking and Retrieval
How to split documents into chunks for retrieval, and how metadata filters, score thresholds, hybrid search and reranking change what the model receives.
On this page
Chunking is the step that splits your documents into pieces before they are embedded and stored for retrieval-augmented generation. Retrieval then picks the few chunks that are sent to the model along with the question. Both steps decide what the model gets to see, so a bad chunk or a bad retrieval setting produces a bad answer even when the model itself is fine.
Suppose a recipe book is cut into pieces of exactly 100 words. One piece ends with "Bake at" and the next starts with "180°C for 25 minutes". A search for how long the lemon cake bakes will not find the second piece, because it never mentions lemon cake, and the first piece does not contain the answer.
How chunk size affects retrieval
Each chunk is turned into one embedding vector, and that single vector has to represent everything in the chunk. This is why size matters in both directions.
A chunk that is too large covers several topics. Its vector is a blend of all of them, so it matches none of them strongly, and when it is retrieved it fills the context with text the question did not need.
A chunk that is too small loses its subject: "Bake for 25 minutes" says nothing without the recipe it belongs to.
For ordinary prose, a paragraph or a short section of a few hundred tokens is a reasonable starting size. The more reliable test is whether a person could read the chunk with no other context and understand what it is about and what it claims.
Chunking methods
Fixed-size chunks with overlap
This method takes a window of a fixed number of words or tokens and moves it forward by less than its own length, so that neighbouring chunks share some text. It works on any text, including text with no structure at all. The overlap means that a sentence cut at the edge of one chunk appears whole in the next one.
The tracer below splits a 15-word sentence with a window of 6 words and an overlap of 2.
step = size - overlapfor start = 0, step, 2·step, ...: chunk = words[start : start + size] if start + size >= length: stop- words0Bake1the2lemon3cake4at5180°C6for7258minutes9then10let11it12cool13before14icing
- size
- 6
- overlap
- 2
- step
- 4
- chunks
- 0
1The text has 15 words. With size 6 and overlap 2, each window starts 6 − 2 = 4 words after the previous one.
- words0Bakestart1the2lemon3cake4at5180°C6for7258minutes9then10let11it12cool13before14icing
- size
- 6
- overlap
- 2
- step
- 4
- chunks
- 1
2Chunk 1 is words 0 to 5, "Bake the lemon cake at 180°C". Since 0 + 6 = 6 is less than 15, the loop continues.
- words0Bake1the2lemon3cake4atstart5180°C6for7258minutes9then10let11it12cool13before14icing
- size
- 6
- overlap
- 2
- step
- 4
- chunks
- 2
3Chunk 2 is words 4 to 9, "at 180°C for 25 minutes then". Words 4 and 5 are in both chunks, so the temperature stays next to the time.
- words0Bake1the2lemon3cake4at5180°C6for7258minutesstart9then10let11it12cool13before14icing
- size
- 6
- overlap
- 2
- step
- 4
- chunks
- 3
4Chunk 3 is words 8 to 13, "minutes then let it cool before".
- words0Bake1the2lemon3cake4at5180°C6for7258minutes9then10let11it12coolstart13before14icing
- size
- 6
- overlap
- 2
- step
- 4
- chunks
- 4
5Chunk 4 is words 12 to 14, "cool before icing". Since 12 + 6 = 18 is past the end, the loop stops. A short final chunk is normal.
- words0Bake1the2lemon3cake4at5180°C6for7258minutes9then10let11it12cool13before14icing
- chunks
- 4
- without overlap
- 3
6The result is four chunks instead of the three that you would get without overlap. Chunk 2 holds the baking time, but it never mentions lemon cake, so overlap alone does not fix the missing subject. That needs the context prefix described below.
function chunkWords(text, size, overlap) {
const words = text.split(/\s+/);
const step = size - overlap; // must be at least 1
const chunks = [];
for (let start = 0; start < words.length; start += step) {
chunks.push(words.slice(start, start + size).join(" "));
if (start + size >= words.length) break;
}
return chunks;
}
chunkWords("Bake the lemon cake at 180°C for 25 minutes then let it cool before icing", 6, 2);
// 4 chunks, the second is "at 180°C for 25 minutes then"def chunk_words(text, size, overlap):
words = text.split()
step = size - overlap # must be at least 1
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunks
chunk_words("Bake the lemon cake at 180°C for 25 minutes then let it cool before icing", 6, 2)
# 4 chunks, the second is "at 180°C for 25 minutes then"Overlap increases the number of chunks, and fixed-size chunking fails when it cuts through a table, a code block or a numbered procedure. Real systems count tokens, not words, with an overlap of roughly a tenth to a fifth of the window. Use it as the fallback.
Splitting by document structure
Most documents already have natural boundaries, and splitting on them gives chunks that are self-contained without any tuning. The usual approach is to split on headings first, then on paragraphs inside a long section, and to fall back to fixed-size windows only for a paragraph that is still too long.
Each kind of document has its own unit. An FAQ becomes one chunk for each question together with its answer. Source code is split by function or class. A table is kept whole, or split by row groups with the header row repeated in each group, because a row without its column names cannot be understood.
Use this method whenever the documents have reliable structure. Its weakness is that sections vary a lot in length, so a few very long sections still need a size limit, and a few very short ones may need to be merged with their neighbours.
Adding context to each chunk
A chunk taken out of its document loses information that the surrounding text provided, such as the title, the section and the product it describes. The fix is to put that information back, in two ways.
The first is a prefix that is embedded together with the text, for example "Lemon cake > Baking: at 180°C for 25 minutes". The prefix gives the embedding the subject that the sentence itself lacks, so the chunk now matches a question about lemon cake.
The second is metadata stored next to the chunk but not embedded: the source title, section, date, product, version and access rights. Metadata does not help the vector match, but it lets retrieval filter exactly, and it lets the answer cite where the text came from.
Semantic chunking
Some text has no headings, such as a transcript or a long email thread. Semantic chunking handles it by embedding each sentence and starting a new chunk where the similarity between neighbouring sentences drops sharply, which usually marks a change of topic. It produces chunks that follow the content instead of a character count, but it costs an embedding call for every sentence at indexing time and the drop threshold needs tuning. Use it only for unstructured text where fixed windows cut topics in the wrong places.
Retrieval techniques
The simplest retrieval embeds the question and returns the top k chunks by cosine similarity. That is a reasonable first version. Each technique below fixes one specific failure of it, so add them when you see the failure and not before.
Metadata filters
A filter restricts the search to chunks whose metadata matches, such as one product, one language or one customer. Filters are exact and cheap. Without one, a chunk about a different product that happens to use similar words can outrank the correct chunk. Filters on access rights are also how you keep one user's documents out of another user's answers, which is a correctness requirement and not a tuning option.
Minimum score threshold
Top k always returns k chunks, even when nothing in the index is relevant, and the model will treat whatever it receives as relevant. A minimum similarity score lets retrieval return fewer chunks, or none, so that the model can be told that nothing was found. Choose the threshold by looking at the scores of questions that should and should not be answerable.
Hybrid search
Embeddings capture meaning but are weak at exact strings such as error codes, part numbers, function names and people's names. Keyword search is the opposite: it finds exact strings but misses paraphrases. Hybrid search runs both and merges the two ranked lists, commonly by combining the rank of each result in each list. Use it when users search for identifiers or when documents use specialist vocabulary.
Reranking
A reranker is a slower model that reads the question and one candidate chunk together and scores how well the chunk answers the question. Because it is slow, it is applied only to the candidates from the first search: retrieve 20 to 50 cheaply, rerank them, and keep the best 3 to 5. This helps when the right chunk is usually in the candidates but not at the top. It does not help when the right chunk is missing from the candidates, which is a chunking or search problem. It also adds latency to every question.
Query rewriting
In a conversation, a message such as "and for the blue one?" cannot be searched on its own. Before retrieval, have the model rewrite the message into a standalone question using the conversation so far, and search with the rewritten question. It adds one model call, so use it for chat interfaces and skip it for single-question search boxes.
Returning the surrounding section
Small chunks match a question precisely, but a small chunk often lacks the sentences around it that the model needs to answer. One fix is to embed small chunks and, once one is retrieved, send the model its whole parent paragraph or section instead. This is sometimes called small-to-big retrieval. It keeps the precise match and gives the model enough text, at the cost of a larger prompt and of having to store the link from each chunk to its parent.
The code below shows a metadata filter, a score threshold and top k together. It uses the cosine function from RAG Basics. The vectors are toy ones with three dimensions, roughly "cleaning", "indicator lights" and "filling".
const dot = (a, b) => a.reduce((s, x, i) => s + x * b[i], 0);
const cosine = (a, b) => dot(a, b) / Math.sqrt(dot(a, a) * dot(b, b));
function retrieve(queryVec, chunks, { product, k, minScore }) {
return chunks
.filter((c) => c.product === product)
.map((c) => ({ text: c.text, score: cosine(queryVec, c.vec) }))
.filter((c) => c.score >= minScore)
.sort((a, b) => b.score - a.score)
.slice(0, k);
}
const manual = [
{ product: "kettle", text: "Kettle > Care: descale monthly with vinegar.", vec: [5, 0, 1] },
{ product: "kettle", text: "Kettle > Lights: red means boiling.", vec: [1, 4, 0] },
{ product: "toaster", text: "Toaster > Care: empty the crumb tray weekly.", vec: [4, 1, 1] },
{ product: "kettle", text: "Kettle > Filling: never fill above MAX.", vec: [1, 1, 4] },
];
// "How do I clean the kettle?" embeds to [5, 1, 0]
retrieve([5, 1, 0], manual, { product: "kettle", k: 2, minScore: 0.5 });
// [{ text: "Kettle > Care: ...", score: 0.96 }]import math
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def cosine(a, b):
return dot(a, b) / math.sqrt(dot(a, a) * dot(b, b))
def retrieve(query_vec, chunks, product, k, min_score):
scored = [
{"text": c["text"], "score": cosine(query_vec, c["vec"])}
for c in chunks if c["product"] == product
]
scored = [c for c in scored if c["score"] >= min_score]
scored.sort(key=lambda c: c["score"], reverse=True)
return scored[:k]
manual = [
{"product": "kettle", "text": "Kettle > Care: descale monthly with vinegar.", "vec": [5, 0, 1]},
{"product": "kettle", "text": "Kettle > Lights: red means boiling.", "vec": [1, 4, 0]},
{"product": "toaster", "text": "Toaster > Care: empty the crumb tray weekly.", "vec": [4, 1, 1]},
{"product": "kettle", "text": "Kettle > Filling: never fill above MAX.", "vec": [1, 1, 4]},
]
# "How do I clean the kettle?" embeds to [5, 1, 0]
retrieve([5, 1, 0], manual, "kettle", k=2, min_score=0.5)
# [{'text': 'Kettle > Care: ...', 'score': 0.96}]Without the filter, the toaster's care chunk would score 0.97 and win, because cleaning instructions look alike across products. Among the kettle chunks, care scores 0.96, lights 0.43 and filling 0.28. The threshold of 0.5 removes the last two, so the function returns one chunk even though k is 2, which is the intended behaviour when only one chunk is relevant.
Pitfalls
Choosing settings and measuring retrieval
Start with the structure of your documents and not with a number. Split on headings or on the natural unit of each document type, add the title and section as a prefix, and store metadata for anything you might want to filter on. Then adjust size and overlap using measurements.
To measure, write 20 to 50 real questions and note which chunk contains the answer to each. Run retrieval on its own, without the model, and count how often the correct chunk appears in the top k. Repeat this after every change to chunk size, overlap, filters or ranking. If the right chunk is never retrieved, the problem is in chunking or search, and changing the prompt will not help. If it is retrieved but the answer is still wrong, look at the prompt and the model instead. Evals describes how to turn this into a routine check.
Questions people ask about retrieval
The answer is wrong. How do you tell whether retrieval or generation is at fault?
Look at the retrieved chunks for that question. If the correct text is not among them, retrieval is the problem, and the fix is in chunking, filters, hybrid search or the query. If the correct text was retrieved and the model still answered wrongly, the problem is in the prompt or the model.
What happens if you change the embedding model?
Every chunk has to be embedded again, because vectors from different models cannot be compared with each other. Keep the original text and the model name for each chunk, so that re-indexing is a batch job and not a rebuild from the source documents.
You are indexing a gym's 40-question FAQ. Each entry is a bold question followed by an answer of one to three paragraphs. Some answers say things like "Yes, as above, but only at weekends." How would you chunk it, what would you store with each chunk, and how would you handle answers like that?
Show a sample answer
Make each question and its answer one chunk, and include the question text. Users tend to phrase their questions the way the FAQ does, so the question is often the best text to match. The entries are already self-contained, so fixed-size splitting is needed only for an answer that is unusually long.
Prefix each chunk with its path, for example "Gym FAQ > Memberships > Can I bring a guest?", and store the section, the gym location if there are several, and the last-updated date as metadata.
Rewrite the "as above" answers while indexing so that each one stands alone, for example "Yes, guests are allowed, but only at weekends." Alternatively, attach the answer that it refers to. A retrieved chunk that says "as above" gives the model nothing to work with.
With 100 words, size 10 and overlap 5, about how many chunks do you get?
Users search for error codes like E-4012 and get the wrong troubleshooting page. What helps most?
Why did the kettle example return one chunk when k was 2?
What to practise next
Memory applies the same retrieval ideas to what a model stores about a user or project across many conversations, and Evals shows how to build the question set that measures retrieval.