Chunking
Summary
Chunking is cutting large documents into small fragments (chunks) before storing them in a vector DB.
Why cut documents up
A model cannot 'swallow' a 500-page document whole. On top of that, the vector of a giant document comes out 'blurry': all the topics are mixed together in a single vector. So the text is cut into pieces, and each piece gets its own embedding.
Rules for good chunking
- Size: optimally 512–1024 tokens per chunk.
- Overlap: 10–15% (50–100 tokens), so that the meaning is not torn apart at the joins.
- Respect the structure: cut by headings and paragraphs, not by a fixed number of characters.
Tools in LangChain
RecursiveCharacterTextSplitter— splits first by headings, then by paragraphs, then by sentences. The default choice.MarkdownHeaderTextSplitter— extracts the structure of the document and enriches each chunk with metadata (chapter, section, page).
An advanced technique: Parent-Document Retriever
Small chunks (200 tokens) are used for precise search. But the 'parent' large block (2000 tokens) to which the found piece belongs is passed into the prompt. This solves the problem of losing context.