Evaluating Chunking Strategies

Measure which chunking strategy actually retrieves better on your data.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 4 · Lesson 9 of 10 · Intermediate

Evaluating Chunking Strategies

Measure which chunking strategy actually retrieves better on your data.

Every chunking lesson so far has ended with "measure it on your data". This lesson shows how. You will build a small evaluation harness that compares chunking strategies by how often they retrieve the passage that answers each test question.

What to measure

Chunking affects retrieval, so evaluate retrieval directly. You do not need the LLM in the loop for this, which makes the experiment fast and cheap.

  • Hit rate@k: the share of questions for which at least one of the top k chunks contains the answer.
  • MRR (mean reciprocal rank): rewards putting the answering chunk near the top. A hit at rank 1 scores 1, at rank 2 scores 0.5, at rank 3 scores 0.33, and so on.
  • Context size: the average number of characters (or tokens) in the top k chunks. A strategy that wins only by sending three times more text is not really better.

Step 1: A small test set

For each question, record a short evidence string: a phrase that must appear in a chunk for that chunk to count as answering the question. Twenty to fifty questions written by someone who knows the documents are enough to compare strategies. The lesson Building a Golden Test Set shows how to generate them with an LLM.

chunk_eval.py
TEST_SET = [
    {"question": "How many paid leave days do first-year employees get?", "evidence": "18 days of paid leave"},
    {"question": "Can unused leave be carried over?", "evidence": "carried over"},
    {"question": "When is a medical certificate needed?", "evidence": "medical certificate"},
    {"question": "How much is the internet reimbursement?", "evidence": "1,500 rupees"},
    {"question": "Which day do engineers usually work from home?", "evidence": "Fridays"},
    {"question": "What is the hotel limit in metro cities?", "evidence": "6,000 rupees"},
    {"question": "Who approves large expense claims?", "evidence": "department head"},
]

Step 2: The harness

import numpy as np
from pathlib import Path
from rag_helpers import embed

def normalise(s: str) -> str:
    return " ".join(s.lower().split())

def evaluate(chunker, documents: dict[str, str], test_set: list[dict], k: int = 3) -> dict:
    chunks = [c for text in documents.values() for c in chunker(text)]
    vectors = embed(chunks)
    query_vectors = embed([t["question"] for t in test_set], query=True)

    hits, reciprocal_ranks, context_sizes = 0, [], []
    for test, q in zip(test_set, query_vectors):
        top = np.argsort(-(vectors @ q))[:k]
        context_sizes.append(sum(len(chunks[i]) for i in top))
        rank = next((r for r, i in enumerate(top, start=1)
                     if normalise(test["evidence"]) in normalise(chunks[i])), None)
        hits += rank is not None
        reciprocal_ranks.append(1 / rank if rank else 0.0)

    return {
        "chunks": len(chunks),
        f"hit_rate@{k}": round(hits / len(test_set), 3),
        "mrr": round(float(np.mean(reciprocal_ranks)), 3),
        "avg_context_chars": int(np.mean(context_sizes)),
    }

Step 3: Compare strategies

from chunkers import recursive_split, add_overlap     # fixed-size chunking lesson
from semantic_chunker import semantic_chunks          # semantic chunking lesson

documents = {p.name: p.read_text(encoding="utf-8") for p in Path("docs").glob("*.txt")}

strategies = {
    "fixed 200 chars":        lambda t: [t[i:i + 200] for i in range(0, len(t), 200)],
    "recursive 300":          lambda t: recursive_split(t, 300),
    "recursive 300 + overlap": lambda t: add_overlap(recursive_split(t, 300), 60),
    "recursive 800":          lambda t: recursive_split(t, 800),
    "semantic":               lambda t: semantic_chunks(t, percentile=80),
}

print(f"{'strategy':26} {'chunks':>6} {'hit@3':>6} {'mrr':>6} {'context':>8}")
for name, chunker in strategies.items():
    r = evaluate(chunker, documents, TEST_SET)
    print(f"{name:26} {r['chunks']:>6} {r['hit_rate@3']:>6} {r['mrr']:>6} {r['avg_context_chars']:>8}")
strategy                   chunks  hit@3    mrr  context
fixed 200 chars                 9  0.714  0.571      600
recursive 300                   9  1.0    0.857      742
recursive 300 + overlap         9  1.0    0.929      908
recursive 800                   3  1.0    1.0     1859
semantic                        8  1.0    0.857      812

These numbers come from the tiny sample collection, so read them as an illustration of the method, not as a verdict. Even here, the pattern is typical: naive fixed-size chunking cuts evidence in half and misses answers, while the "recursive 800" strategy wins on MRR only because the whole collection fits in three chunks, so it sends more than twice as much text per query. On a real collection with hundreds of documents, large chunks usually lose precision.

Reading the results

  • Pick the strategy with the best hit rate and MRR at an acceptable context size.
  • Look at the failures, not just the averages. Print the questions that missed and the chunks that were retrieved instead. Failures usually show a pattern, such as split tables, missing headings or answers that span two sections.
  • Re-run the comparison whenever your documents change in character, such as a new source or format.
Tip

Evidence matching by substring is simple and transparent, but strict. If a strategy rewrites text (for example by adding headers), the evidence still matches. If your evidence strings are long, matching can fail because of whitespace or line breaks, which the normalise() function handles.

Key takeaways

  • Evaluate chunking with retrieval metrics: hit rate@k, MRR and context size.
  • A small set of questions with evidence strings is enough to compare strategies.
  • Prefer the strategy that retrieves best at a reasonable context size, and study the failures.