Sub topic 8
Chunking long documents for embedding
This chapter assumes you can write basic Python, know what an embedding is, and have generated embeddings with a pretrained model. Chunking is the step between your raw documents and the embedding model.
Why documents need chunking
Embedding models accept a limited number of tokens. A model like all-MiniLM-L6-v2 truncates its input at 256 word pieces by default. Anything past that limit is silently dropped, so the end of a long document never influences its vector.
Length also hurts quality. One vector for a 10-page document averages many topics into a blurry point. A query about a single detail then matches poorly. Smaller chunks give each vector a narrower meaning, so search can return the passage that answers the question instead of the whole file.
The trade-off in chunk size
Chunk size is a balance.
| Chunk size | Benefit | Cost |
|---|---|---|
| Small (50 to 100 words) | Precise matches | Loses surrounding context |
| Medium (150 to 300 words) | Good balance for most prose | Needs tuning per corpus |
| Large (500+ words) | Keeps context together | Blurry vectors, may exceed the model limit |
Start with a size that fits comfortably under the model's token limit, then adjust using retrieval metrics.
Fixed-size chunks with overlap
The simplest method splits text into windows of a fixed number of words. If a sentence falls on a boundary, it is cut in half and neither chunk captures it well. Overlap fixes this by repeating the last few words of one chunk at the start of the next.
def chunk_words(text, chunk_size=200, overlap=40):
if overlap >= chunk_size:
raise ValueError("overlap must be smaller than chunk_size")
words = text.split()
step = chunk_size - overlap
chunks = []
for start in range(0, len(words), step):
chunks.append(" ".join(words[start:start + chunk_size]))
if start + chunk_size >= len(words):
break
return chunksThe window moves forward by step = chunk_size - overlap words. The break stops the loop once a chunk reaches the end of the text. Without it, the loop would add a short final chunk made only of text already covered.
text = " ".join(f"w{i}" for i in range(500))
chunks = chunk_words(text, chunk_size=200, overlap=40)
print(len(chunks)) # 3
print(chunks[0].split()[-1]) # w199
print(chunks[1].split()[0]) # w160Chunk 0 ends at w199, and chunk 1 starts at w160. The 40 words in between appear in both chunks.
Structure-aware chunking
Words are a rough unit. Documents often have natural boundaries such as paragraphs, headings, and list items. Splitting on these keeps related sentences together. A common approach is to split on paragraphs first, then merge small paragraphs or split large ones until each chunk fits your size target. Libraries such as LangChain offer recursive splitters that follow this idea.
Keep track of where chunks come from
Store metadata with each chunk: the source document id, the position, and the section title if you have one. At query time you can show the user the source, fetch neighboring chunks for more context, and merge several hits from the same document.
Common mistakes
- Counting words when the limit is in tokens. One word is often more than one token, so a 200-word chunk may exceed a 256-token limit. Use the model's tokenizer to check lengths if you are close to the limit.
- Setting overlap too high. With 50% overlap you store about twice as many vectors for little gain. An overlap of 10 to 20 percent is a common starting point.
- Embedding chunks with no context. A chunk reading "It increased by 8%" has no subject. Prepending the document title to each chunk often helps.
Exercise
You call chunkwords on a text of 1,000 words with chunksize=250 and overlap=50. How many chunks do you get, and which word positions (starting from 0) does the second chunk cover?
Show answer
The step is 250 - 50 = 200, so chunks start at positions 0, 200, 400, 600, and 800. The chunk starting at 800 covers positions 800 to 999 and reaches the end, so the loop stops there. That gives 5 chunks. The second chunk starts at 200 and covers positions 200 to 449.