Chunking Documents

Updated · 5 min read
mediumPython 3.13airagchunkingembeddingspython

Chunking is splitting documents into smaller passages, called chunks, before embedding them. It is used because retrieval matches one vector per chunk: a chunk should hold one complete idea, small enough to match a specific question and large enough to make sense on its own. Overlap repeats a few words between neighboring chunks so an idea cut at a boundary still appears whole in one of them.

Too Small, Too Large, Just Right

Chunk size changes what retrieval finds
Chunk sizeProblemEffect on retrieval
Too smallLoses context, such as which claims are "paid"Matches weakly or misleads
Too largeMixes many ideas in one vectorScores blur; the model gets extra text to read
About a paragraphOne complete ideaUsually the best match

Syntax

StrategyDescription
By paragraphIt is used when documents have clear paragraphs, as in "Building a RAG Pipeline"
By fixed size with overlapIt is used for long text without clear structure
By heading or sectionIt is used for manuals and policies with headings, keeping each heading with its text

Example: Comparing Chunk Sizes

This program uses the docs folder from "Building a RAG Pipeline":

Python
from pathlib import Path
 
from sentence_transformers import SentenceTransformer
 
def chunk_words(text, size, overlap=0):
    """Split text into chunks of `size` words; neighbors share `overlap` words."""
    words = text.split()
    step = size - overlap
    return [" ".join(words[i:i + size]) for i in range(0, max(len(words) - overlap, 1), step)]
 
text = Path("docs/travel-policy.md").read_text().split("\n", 1)[1]  # skip the title line
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
question = model.encode("How fast are travel claims paid?", normalize_embeddings=True)
 
for size, overlap in [(8, 0), (8, 3), (30, 5), (200, 0)]:
    chunks = chunk_words(text, size, overlap)
    scores = model.encode(chunks, normalize_embeddings=True) @ question
    best = chunks[scores.argmax()]
    found = "two pay periods" in best
    print(f"size {size:3}, overlap {overlap}: {len(chunks):2} chunks | best {scores.max():.2f} | answer inside: {found}")
    print("   ", best[:90] + ("..." if len(best) > 90 else ""))
Output
size   8, overlap 0: 10 chunks | best 0.47 | answer inside: True
    paid within two pay periods.
size   8, overlap 3: 15 chunks | best 0.64 | answer inside: True
    claims are paid within two pay periods.
size  30, overlap 5:  3 chunks | best 0.77 | answer inside: True
    are not reimbursed. Submit claims within 30 days of the trip through the finance portal, w...
size 200, overlap 0:  1 chunks | best 0.52 | answer inside: True
    Staff who use a personal car for approved school trips are paid 70 cents per mile. On over...

Explanation: chunk_words() cuts the policy every size words, stepping back overlap words each time. With 8-word chunks, the best match is "paid within two pay periods." It contains the answer but not what is paid, and it scores only 0.47. Three words of overlap bring "claims" back into the chunk (0.64). Thirty-word chunks hold the whole claims paragraph and score highest (0.77). One chunk for the whole document scores 0.52, because the answer is buried among mileage, meals and hotels.

Giving Small Chunks Context

Small chunks match precisely but can lose what they are about.

Common Mistakes

Choosing a chunk size without testing. Try a few sizes on real questions, as this lesson does.

Splitting tables and lists in the middle. Keep a table, or a numbered list, in one chunk where possible.

Dropping the source and position. Store the file name and section with every chunk for citations.

Interview Corner

Why does chunk size matter in RAG?

Each chunk becomes one vector. Chunks that are too small lose context; chunks that are too large mix many ideas and blur the match. Test sizes on real questions.

What is chunk overlap for?

Repeating a few words between neighboring chunks so that an idea cut at a boundary still appears whole in one chunk.

Practice

Exercise: chunk by paragraph and by heading. Run the comparison for the question "Are hotel upgrades paid for?" Which size wins this time? Then try chunking by paragraph and compare the best score.

Check your understanding:

  1. What is a chunk?
  2. Why did the 8-word chunk score lower than the 30-word chunk?
  3. What does overlap add?

Quick check: chunking

4 questions
1Which chunk size scored highest in the example?
2What went wrong with the whole-document chunk?
3What does overlap do?
4What makes a good chunk?

Key Takeaways

Quick reference

NeedApproach
Clear paragraphsChunk by paragraph
Long unstructured textFixed size with overlap
Manuals and policiesChunk by section, heading included

Was this tutorial helpful?

Lesson 97 of 186