Sub topic 8
Chunking long documents for embedding
An embedding model turns a piece of text into one vector. A long document is a poor fit for that. This chapter explains why, and how to split documents into chunks that embed well and retrieve well. It assumes you can run the earlier examples: you know how to call model.encode, you know what a unit-length vector is, and you have seen exact top-k search with a matrix product.
Why documents must be split
There are two separate reasons to chunk. They pull in different directions.
- Input limits. Every embedding model reads at most a fixed number of tokens. A token is a word or word piece produced by the model's tokenizer.
all-MiniLM-L6-v2has a limit of 256 tokens. The library truncates anything longer without raising an error, so the tail of a long document is never embedded. - Dilution. Even when a model accepts a long input, the result is one vector for the whole text. That vector averages every topic in the text. A 3,000-word manual that covers ten subjects gives a vector that sits in the middle of all ten and matches none of them well.
Small chunks give focused vectors, so precision is high. But a chunk that is too small loses the context that makes it understandable. A sentence such as "It must be renewed every 90 days" is useless once you cannot tell what "it" refers to.
You are choosing a chunk size between those two failures.
Measuring size in tokens, not words
The limit is in tokens, but it is easier to write chunkers that count words. A word often becomes more than one token, especially for rare words, code, and identifiers. Use the model's own tokenizer to check how well your word-based sizes fit.
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
print(model.max_seq_length) # 256
def token_count(text):
return len(model.tokenizer.tokenize(text))
sample = "Reciprocal rank fusion merges rankings without normalizing scores."
print(len(sample.split()), token_count(sample))For ordinary English prose, expect roughly 1.3 tokens per word. A 200-word chunk is therefore about 260 tokens, which already goes past the 256-token limit of this model. Technical text with code or long identifiers can use many more tokens per word. Pick a word budget that leaves headroom, or count tokens directly.
Fixed-size chunks with overlap
The simplest strategy is to cut the word list into windows of a fixed length. Neighboring windows share some words. That overlap means a sentence cut at one boundary still appears whole in the next chunk.
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 advances by step = chunk_size - overlap words each time. For a 500-word document with the defaults, the step is 160 and the chunks cover words 0 to 200, 160 to 360, and 320 to 500. The break stops the loop as soon as a chunk reaches the end of the text. Without it, you would get a final chunk that only repeats the tail of the previous one.
The overlap >= chunk_size check matters. With an overlap equal to the chunk size, the step is zero and range raises an error. With a larger overlap the step is negative, so range produces no chunks and you silently lose the whole document.
Fixed windows are easy to reason about and work on any text. Their weakness is that they ignore structure. They will cut in the middle of a sentence, a table row, or a code block.
Respecting sentence boundaries
A better default for prose is to fill each chunk with whole sentences up to a budget. This avoids cutting mid-sentence and needs no overlap for the cut-sentence problem.
import re
def chunk_sentences(text, max_words=150):
if not text.strip():
return []
sentences = re.split(r"(?<=[.!?])\s+", text.strip())
chunks, current, count = [], [], 0
for sentence in sentences:
n = len(sentence.split())
if current and count + n > max_words:
chunks.append(" ".join(current))
current, count = [], 0
current.append(sentence)
count += n
if current:
chunks.append(" ".join(current))
return chunksThe regular expression splits after ., !, or ? followed by whitespace. It is crude. It will split after "Dr." or "e.g.", and it knows nothing about abbreviations or decimals. A sentence-splitting library handles these better. A single sentence longer than max_words still becomes one oversized chunk, so check for that if your input can contain run-on text.
Chunking along document structure
Real documents have structure that marks natural topic boundaries: headings, paragraphs, list items, and code blocks. When your source is Markdown, HTML, or a PDF with extractable headings, split on that structure first. Only split further when a section exceeds the budget.
A common recursive approach tries separators from coarse to fine. It splits on blank lines first, then on single newlines, then on sentence ends, then on spaces. At each level it keeps the pieces that fit and splits only the ones that do not. Libraries such as LangChain and LlamaIndex ship this as a ready-made splitter. The idea is simple enough to write yourself when you need control.
Keep context with metadata
A chunk often needs information that is not in its own text. The usual fix is to store metadata beside each vector, and sometimes to include it in the embedded text.
def make_records(doc_id, title, chunks):
records = []
for i, chunk in enumerate(chunks):
records.append({
"id": f"{doc_id}-{i}",
"doc_id": doc_id,
"position": i,
"text": chunk,
"embed_text": f"{title}\n{chunk}",
})
return records
records = make_records("manual-7", "Router setup guide",
["Hold the reset button for ten seconds.",
"Then open the admin page."])
print(records[0]["embed_text"])The embed_text field prepends the document title, so a chunk that says "Hold the reset button for ten seconds" is embedded together with the fact that it concerns a router. The original text is what you show to the user. The doc_id and position fields let you do two useful things later: fetch the neighboring chunks for more context, and collapse several hits from the same document into one result.
Choosing size and overlap
There is no universally correct chunk size. These are common starting points, and you should treat them as hypotheses to test.
| Setting | Typical range | Effect of going lower | Effect of going higher |
|---|---|---|---|
| Chunk size | 100 to 300 words | Sharper vectors, less context per hit | More topics blended into one vector, risk of truncation |
| Overlap | 10% to 20% of chunk size | Fewer duplicates, more boundary cuts | More index size and repeated hits |
| Number of results (k) | 3 to 10 | Misses relevant chunks | Adds noise, longer prompts in RAG |
Overlap has a cost. A 20% overlap makes the index about 25% larger, because each stretch of text is stored more than once. Search results will also often contain two adjacent chunks that share text. De-duplicating by doc_id and position solves that.
Match the chunk size to the queries as well as the documents. Short factual questions ("What is the default port?") retrieve best from small chunks. Broad questions ("How does the billing system work?") need larger chunks, or retrieval of neighbors.
Common failure modes
- Silent truncation. Chunks exceed the model's token limit, so their endings are not embedded. Check token counts against
max_seq_length. - Orphan fragments. The last chunk of a document may be only a few words, and its vector is noisy. Merge tiny trailing chunks into the previous one.
- Lost referents. Pronouns and phrases like "the above table" lose meaning when the chunk stands alone. Add titles or section headings through metadata.
- Destroyed structure. Splitting inside a code block or table row makes both halves unreadable. Split on structure first.
- Duplicate hits. High overlap returns the same passage several times. Group results by document and position.
Chunking choices cannot be judged by inspection alone. Change the chunk size, rebuild the index, and measure recall@k and MRR on a set of labeled queries. The evaluation chapter covers how to do that.
Exercise
A 1,000-word document is split with chunkwords using chunksize=250 and overlap=50. How many chunks does it produce, and where does each begin? Why is overlap=250 an error?
Show answer
The step is 250 - 50 = 200. Chunks start at words 0, 200, 400, and 600. The chunk starting at 600 covers words 600 to 850 and does not reach the end, so the loop continues. The chunk starting at 800 covers words 800 to 1000, reaches the end, and the loop breaks. That gives five chunks, starting at 0, 200, 400, 600, and 800. An overlap equal to chunk_size makes the step zero, and range() raises an error for a step of zero, so the function rejects it up front.
Exercise
Your model has maxseqlength=256 and your chunks are 220 words of technical documentation containing many identifiers. Search quality is poor for facts near the end of each chunk. What is the most likely cause, and what two changes would you try?
Show answer
The chunks likely exceed 256 tokens, because identifiers split into many word pieces. The model truncates silently, so the end of each chunk is never embedded. First, count tokens with model.tokenizer.tokenize and confirm. Then either reduce the chunk size by words (for example to 120) or switch to a token-based budget, or pick a model with a longer maximum sequence length.