Chunking Documents
Retrieval works on chunks, not whole documents. A 40-page manual embedded as one vector is a blurry average of everything in it; a question about the warranty needs the warranty paragraph. Splitting documents well is one of the most important — and most overlooked — parts of a RAG system.
The trade-off
| Chunk size | Pros | Cons |
|---|---|---|
| Small (a sentence or two) | precise matches | loses surrounding context; answers spread over many chunks |
| Large (several pages) | full context | noisy embeddings; wastes prompt tokens; worse ranking |
| Medium (a paragraph / section, a few hundred tokens) | usually a good starting point | needs tuning per document type |
Fixed-size chunks with overlap
The simplest method cuts every N words. An overlap repeats the last few words of each chunk at the start of the next, so a sentence that straddles a boundary is complete in at least one chunk.
text = ("The X200 kettle has a 1.7 litre capacity. It switches off automatically when the water boils. "
"Descale it every month in hard-water areas. The warranty lasts two years from the date of purchase. "
"To claim the warranty, contact support with your receipt.")
def chunk_words(text, size, overlap):
words = text.split()
step = size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + size]))
if start + size >= len(words):
break
return chunks
for i, c in enumerate(chunk_words(text, size=16, overlap=4)):
print(f"[{i}] {c}")[0] The X200 kettle has a 1.7 litre capacity. It switches off automatically when the water boils.
[1] when the water boils. Descale it every month in hard-water areas. The warranty lasts two years
[2] warranty lasts two years from the date of purchase. To claim the warranty, contact support with
[3] warranty, contact support with your receipt.
Fixed-size cuts ignore meaning: a chunk can start in the middle of a sentence.
Sentence-aware chunks
A better default packs whole sentences into chunks up to a size limit:
import re
text = ("The X200 kettle has a 1.7 litre capacity. It switches off automatically when the water boils. "
"Descale it every month in hard-water areas. The warranty lasts two years from the date of purchase. "
"To claim the warranty, contact support with your receipt.")
def chunk_sentences(text, max_words):
sentences = re.split(r"(?<=[.!?])\s+", text.strip())
chunks, current = [], []
for s in sentences:
if current and len(" ".join(current + [s]).split()) > max_words:
chunks.append(" ".join(current))
current = []
current.append(s)
if current:
chunks.append(" ".join(current))
return chunks
for i, c in enumerate(chunk_sentences(text, max_words=20)):
print(f"[{i}] ({len(c.split())} words) {c}")[0] (16 words) The X200 kettle has a 1.7 litre capacity. It switches off automatically when the water boils.
[1] (17 words) Descale it every month in hard-water areas. The warranty lasts two years from the date of purchase.
[2] (9 words) To claim the warranty, contact support with your receipt.
Structure-aware chunks with metadata
Real documents have structure — headings, sections, pages. Splitting along headings keeps topics together, and storing the heading as metadata lets you show where an answer came from, filter by section, or prepend the heading to the chunk text so it carries its context:
manual = """# Setup
Fill the kettle to at least the MIN mark. Place it on the base.
# Cleaning
Descale every month in hard-water areas. Use vinegar or a descaler.
# Warranty
The warranty lasts two years. Keep your receipt."""
def chunk_by_heading(markdown, source):
chunks, heading, lines = [], None, []
for line in markdown.splitlines() + ["# END"]:
if line.startswith("# "):
if heading and lines:
body = " ".join(l for l in lines if l.strip())
chunks.append({"source": source, "section": heading,
"text": f"{heading}: {body}"})
heading, lines = line[2:], []
else:
lines.append(line)
return chunks
for c in chunk_by_heading(manual, "x200-manual"):
print(c){'source': 'x200-manual', 'section': 'Setup', 'text': 'Setup: Fill the kettle to at least the MIN mark. Place it on the base.'}
{'source': 'x200-manual', 'section': 'Cleaning', 'text': 'Cleaning: Descale every month in hard-water areas. Use vinegar or a descaler.'}
{'source': 'x200-manual', 'section': 'Warranty', 'text': 'Warranty: The warranty lasts two years. Keep your receipt.'}
Practical tips
- Measure in tokens for production (chunk limits and prompt budgets are token-based); words are fine for prototypes.
- Keep metadata: source, title, section, page, date, access permissions. You'll need them for citations and filtering.
- Clean the text first: remove navigation menus, repeated headers/footers and boilerplate that would match every query.
- Tables and code need special care — splitting a table row from its header destroys its meaning.
- Test on real questions: pick a few questions, check whether the chunk containing the answer is retrieved, then adjust size and overlap.
- Contextual chunks: some systems prepend a short, generated description of where the chunk sits in the document ("From the X200 manual, warranty section: …") to improve retrieval.
Tip: There is no universally best chunk size. Start with paragraphs or sections of a few hundred tokens and a small overlap, then let your evaluation results guide changes.
Test yourself
Why add overlap between fixed-size chunks?
- To make the index smaller
- So text that crosses a chunk boundary still appears complete in at least one chunk
- To remove duplicate words
- Overlap is required by embedding models
What is a downside of very large chunks?
- They can't be embedded
- Their embeddings average many topics, so ranking gets noisy and prompts waste tokens
- They are always more accurate
- They break JSON
Why store metadata like section and source with each chunk?
- It is needed for tokenization
- For citations, filtering and adding context to the chunk
- To increase similarity scores
- Metadata replaces the text