Tutorial
Chunking strategies for RAG, tested
Compare fixed-size, heading-based and semantic chunking on the same documents and questions, measure retrieval hit rate, and pick a strategy with evidence.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
Chunking decides what your retriever can find. If the answer to a question is split across two chunks, neither chunk may rank well. If chunks are huge, the right paragraph is diluted by everything around it. Advice online ranges from “always 512 tokens” to elaborate semantic splitters, and almost none of it comes with numbers for your documents.
So measure. This tutorial builds a small golden set of questions, implements three chunking strategies, and compares how often each one puts the evidence for an answer in the top results. The whole thing runs locally with an open embedding model, so you can rerun it every time your documents or your splitter change.
What you are measuring
Retrieval quality, separated from generation. For each question you record a short evidence string: a sentence from the source that contains the answer. A retrieval is a hit if any of the top k chunks contains that evidence. Two numbers come out:
- Hit rate at k: the share of questions where the evidence is in the top k. This is what limits your answer quality; the model cannot use what it is not given.
- MRR (mean reciprocal rank): rewards putting the evidence first rather than fifth.
Also record the number of chunks and their average length. Bigger chunks raise hit rates by stuffing more text into each result, but they cost more tokens per question and give the model more to wade through.
1. Set up
python -m venv .venv && source .venv/bin/activate
pip install "sentence-transformers>=6.3" numpy
The first run downloads BAAI/bge-small-en-v1.5, a small English embedding model that runs fine on a laptop CPU. Use the same model you use in production if you have one; chunking results depend on the embedder.
2. Build the golden set
Create golden.jsonl with one question per line. Write questions the way users ask them, not the way the document phrases them, and copy the evidence exactly from the source:
{"q": "how long do I have to submit expenses?", "evidence": "Expense claims must be submitted within 60 days"}
{"q": "can I work from another country for a month?", "evidence": "Working abroad for more than 14 days requires approval"}
{"q": "who approves a laptop upgrade?", "evidence": "Hardware requests over 1,500 are approved by the IT lead"}
Thirty to fifty questions spread across your documents is enough to see real differences between strategies. Include questions whose answers sit in tables, in lists and at the end of long sections, since those are where chunkers differ. Evaluate RAG with a golden set covers building one at scale.
3. Three chunkers
Create chunkers.py:
# chunkers.py
import re
import numpy as np
def fixed(text: str, size: int = 800, overlap: int = 100) -> list[str]:
"""Fixed windows of characters with overlap. The baseline."""
step = size - overlap
return [text[i : i + size] for i in range(0, max(len(text) - overlap, 1), step)]
def by_headings(text: str, max_chars: int = 1500) -> list[str]:
"""Split on Markdown headings; split long sections on blank lines.
Each chunk keeps its section heading so it makes sense on its own."""
sections = re.split(r"(?m)^(?=#{1,3} )", text)
chunks = []
for sec in sections:
sec = sec.strip()
if not sec:
continue
heading = sec.splitlines()[0] if sec.startswith("#") else ""
if len(sec) <= max_chars:
chunks.append(sec)
continue
current = ""
for para in re.split(r"\n\s*\n", sec):
if current and len(current) + len(para) > max_chars:
chunks.append(current.strip())
current = heading + "\n\n" if heading and not para.startswith("#") else ""
current += para + "\n\n"
if current.strip():
chunks.append(current.strip())
return chunks
def semantic(text: str, model, max_chars: int = 1500, percentile: float = 20) -> list[str]:
"""Split between sentences where the topic shifts: adjacent sentences whose
embeddings are least similar (bottom `percentile`) become boundaries."""
sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+|\n{2,}", text) if s.strip()]
if len(sentences) < 3:
return [text]
emb = model.encode(sentences, normalize_embeddings=True)
sims = np.sum(emb[:-1] * emb[1:], axis=1) # cosine of neighbours
cut = np.percentile(sims, percentile)
chunks, current = [], sentences[0]
for sent, sim in zip(sentences[1:], sims):
if sim < cut or len(current) + len(sent) > max_chars:
chunks.append(current)
current = sent
else:
current += " " + sent
chunks.append(current)
return chunks
What each represents:
- Fixed ignores structure. It is simple and predictable, and it will cut sentences, tables and lists in half.
- By headings follows the author’s structure. Documentation, policies and wikis are usually written in sections that answer one question each, which is exactly the unit you want to retrieve. Repeating the heading in each sub-chunk keeps context.
- Semantic looks for topic shifts using the embedder itself. It needs no structure, so it suits transcripts and unformatted text, but it costs an embedding call per sentence at index time.
4. The evaluation
Create evaluate.py:
# evaluate.py
import json
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
from chunkers import by_headings, fixed, semantic
K = 5
model = SentenceTransformer("BAAI/bge-small-en-v1.5")
docs = {p.name: p.read_text(encoding="utf-8") for p in Path("docs").glob("*.md")}
golden = [json.loads(line) for line in open("golden.jsonl", encoding="utf-8")]
strategies = {
"fixed-800": lambda t: fixed(t, 800, 100),
"fixed-400": lambda t: fixed(t, 400, 50),
"headings": by_headings,
"semantic": lambda t: semantic(t, model),
}
def normalise(s: str) -> str:
return " ".join(s.lower().split())
for name, chunk_fn in strategies.items():
chunks = [c for text in docs.values() for c in chunk_fn(text)]
chunk_emb = model.encode(chunks, normalize_embeddings=True, batch_size=64)
hits, rr = 0, 0.0
for item in golden:
q_emb = model.encode(item["q"], normalize_embeddings=True)
top = np.argsort(-chunk_emb @ q_emb)[:K]
evidence = normalise(item["evidence"])
for rank, idx in enumerate(top, start=1):
if evidence in normalise(chunks[idx]):
hits += 1
rr += 1 / rank
break
n = len(golden)
avg_len = sum(map(len, chunks)) / len(chunks)
print(f"{name:10} hit@{K}={hits / n:.2f} MRR={rr / n:.2f} "
f"chunks={len(chunks):4} avg_chars={avg_len:5.0f}")
Put your documents in docs/ and run:
python evaluate.py
The output is one line per strategy:
fixed-800 hit@5=... MRR=... chunks= ... avg_chars= ...
fixed-400 hit@5=... MRR=... chunks= ... avg_chars= ...
headings hit@5=... MRR=... chunks= ... avg_chars= ...
semantic hit@5=... MRR=... chunks= ... avg_chars= ...
We have left the numbers out on purpose. They depend entirely on your documents, questions and embedder, and published numbers from someone else’s corpus will mislead you. That is the point of running it.
5. Read the results
Compare along three axes, not one:
- Hit rate. The floor for answer quality. Below about 0.8 at k=5, fix retrieval before you touch the prompt.
- Average chunk length times k. That is roughly what each question costs in context. A strategy that wins by 2 points with chunks three times larger may not be worth it.
- The misses. Print the questions each strategy missed. You will usually find patterns: tables split from their headers, definitions far from the term, answers in the last paragraph of a long section.
Then change one thing at a time and rerun. Typical next experiments:
- Chunk size for the winning strategy (try half and double).
- Adding the document title and section path to every chunk before embedding.
- Contextual retrieval: prepending a short model-written summary of where each chunk sits in its document, an approach Anthropic described in its contextual retrieval write-up.
- Hybrid search: adding keyword matching for exact terms, covered in Hybrid search and reranking in Postgres.
What tends to hold
Your numbers decide, but some patterns are common enough to try first:
- Structured documents (docs, policies, specs) usually do well with heading-based chunking, because authors already grouped related facts.
- Overlap helps fixed-size chunking but rarely makes it beat structure-aware splitting on structured text.
- Semantic chunking earns its index-time cost on long unstructured text such as transcripts. On well-structured Markdown it often lands close to heading-based splitting.
- Tables need special handling. Keep each table whole with its heading, or convert rows to sentences, rather than letting a splitter cut through them.
Pitfalls
Tuning on the questions you test with. If you adjust the chunker until every golden question passes, you have overfitted. Keep a few questions aside and check them only at the end.
Changing the embedder mid-experiment. Chunking results are specific to the embedding model. Fix it first.
Ignoring document parsing. If your PDFs come out as one line per word, no chunker will save you. Look at the extracted text before chunking it.
Measuring only end answers. A good model can paper over weak retrieval on easy questions and then fail on hard ones. Measure retrieval separately, as here.
Next steps
- Add keyword search and a reranker in Hybrid search and reranking in Postgres.
- Put the golden set into CI with Evaluate RAG with a golden set.
- If retrieval still misses after rechunking, check the other causes in the RAG troubleshooting cheat sheet.
- Decide whether you need RAG at all in RAG vs long context vs fine-tuning.
- Compare vector stores in pgvector vs Pinecone, Qdrant and Weaviate.
- Revisit how the whole pipeline fits together in RAG fundamentals: what RAG is and how it works.
- Store and query the chunks in Postgres with embeddings and vector search.
Covers
- Tools
Check your understanding
Chunking strategies for RAG quiz
Measuring retrieval with hit rate and MRR, fixed versus heading-based versus semantic chunking, and avoiding overfitting.
7 questions · pass mark 70%
Review
Related
- RAG fundamentals: retrieval before generation
What RAG is and how retrieval-augmented generation works, when it beats long context or fine-tuning, and a minimal working pipeline in about 80 lines of Python.
- Hybrid search and reranking in Postgres
Combine Postgres full-text search and pgvector with reciprocal rank fusion in one SQL query, rerank the top results with a cross-encoder, and measure the gain.
- Evaluate RAG answers with a golden dataset
Set up RAG evaluation with a golden dataset and promptfoo: score retrieval, correctness and grounding for every question, and fail CI when answer quality drops.
- Embeddings and vector search, hands on
Embed documents, store them in Postgres with pgvector, index them and run similarity and hybrid search.
- Chunking
Splitting documents into pieces sized for embedding and retrieval, ideally along natural boundaries such as sections or paragraphs.