Document loading & chunking strategies
Parse PDFs and web pages and chunk them so retrieval returns useful passages.
By Invicly Tech, , in AI Engineering with Python. About 12 minutes to read.
In short
Documents are split into chunks before embedding, because whole documents are too long and too broad to retrieve precisely. Chunk size and boundaries strongly affect whether retrieval returns useful passages.
Explained simply
Before you can search your documents by meaning, you have to cut them into pieces. A whole 50-page manual is too long to embed well and far too long to paste into every prompt. The pieces are called chunks, and each one is embedded and retrieved on its own.
Getting clean text out comes first. PDFs and web pages are messy: page numbers, headers, menus, cookie banners and broken tables all end up mixed with the real content. If junk goes in, search returns junk.
Then you decide where to cut. The simplest way is every few hundred tokens with a little overlap, so a sentence near a cut appears in both pieces. A smarter way follows the document's own structure, cutting at headings and sections so each chunk covers one idea.
There is no perfect chunk size for every case. Small chunks are precise but can lose context; big chunks keep context but blur the meaning and fill up the prompt. You find the right size by testing retrieval on real questions.
Press Play on a diagram to walk through it one step at a time.
- Split every N tokens
- Overlap keeps context at edges
- Simple and predictable
- May cut mid-sentence
- Split by headings and sections
- Keeps ideas together
- Chunks vary in size
- Needs clean parsing
- Precise matches
- Can lose surrounding context
- More chunks to store and search
- Cheap to put in the prompt
- Keeps context together
- Embedding blurs several topics
- May exceed the embedder's limit
- Fills the prompt quickly
In depth
Getting clean text out of PDFs
A PDF does not store paragraphs. It stores characters and their positions on a page, so a text extractor must guess the reading order. Two-column layouts can come out interleaved, words split across lines arrive with hyphens, tables become a stream of numbers, and every page repeats its header, footer and page number. Scanned PDFs contain only images and need OCR (optical character recognition) first.
Tools differ: pypdf is simple and pure Python; PyMuPDF is fast and gives layout details such as font sizes, which help find headings; pdfplumber is good at tables; layout-aware tools such as docling or unstructured try to recover headings, lists and tables as structure.
Whatever you use, print the extracted text for a few real documents and read it. Remove repeated headers and footers, rejoin hyphenated words, and keep the page number as metadata for citations.
- Read the extracted text before indexing it
- Strip repeated headers, footers and page numbers
- Keep page numbers as metadata, not content
- Scanned pages need OCR
- 1Load
PDF, HTML, Markdown, Word
- 2Extract text
Keep headings and page numbers
- 3Clean
Drop boilerplate, fix hyphens
- 4Chunk
By structure, then by size
- 5Add metadata
Source, section path, page, date
- 6Embed and store
Vector plus text plus metadata
HTML pages: keep the content, drop the chrome
A web page wraps its real content in menus, sidebars, footers, cookie notices and scripts. Feeding all of that to the embedder adds the same noise to every chunk, which makes unrelated pages look similar.
Use a main-content extractor such as trafilatura, or BeautifulSoup with rules for your site: remove script, style, nav, header and footer elements, then take the main or article element. Keep the heading elements (h1 to h6), because they give you a free structure to chunk by. Converting the page to Markdown-like text is a practical middle ground: headings become # lines, lists stay lists, and links can be kept or dropped.
For your own documentation, it is often better to index the source files (Markdown or similar) directly instead of the rendered HTML.
Size-based chunking done well
Measure chunk size in tokens, not characters, because embedding models have token limits. Common starting sizes are 200 to 800 tokens with 10 to 20% overlap. Check your embedding model's maximum input: many small open models stop at 512 tokens or less, and anything longer is cut off silently, so a 1,000-token chunk would only be half embedded.
Avoid cutting mid-sentence. A recursive splitter tries the biggest natural break first: blank lines between paragraphs. If a piece is still too big, it splits on single line breaks, then on sentences, then on words, and finally merges small neighbouring pieces back up to the target size.
Overlap helps when an answer straddles a boundary, but it duplicates text: with 20% overlap you store and embed about 25% more tokens, and search can return near-duplicate chunks.
- 1Split on blank lines
Paragraphs first
- 2Still too big?
Split on line breaks
- 3Still too big?
Split on sentence ends
- 4Last resort
Split on words
- 5Merge
Join small pieces up to the target size
Structure-aware chunking and context headers
Documents written by people already have structure: titles, sections, subsections, lists, tables and code blocks. Splitting at headings keeps each idea together. Long sections still need size-based splitting inside them, and very short sections can be merged with their neighbours.
Keep tables and code blocks whole when you can; half a table is rarely useful. Then add a context header to each chunk: the document title and the heading path, such as User guide > Billing > Refunds. Prepending it to the chunk text before embedding helps a lot, because a chunk that just says this takes 5 days now carries what this is.
A related pattern is small-to-big retrieval: embed small chunks for precise matching, but when one matches, send the larger parent section to the model so it has the full context.
- 1 Billing
- 1.1 Refunds: chunk 1
- 1.1 Refunds: chunk 2
- 1.2 Invoices: chunk 3
- 2 Account
- 2.1 Passwords: chunk 4
- 2.2 Two-factor login: chunk 5
- 3 Limits
- Table kept whole: chunk 6
Comparing chunk sizes with real questions
Do not pick a chunk size by feel. Write 30 to 50 real questions, and for each note where the answer lives: the document and a short exact phrase from the answer. Then build an index for each setting you want to compare, for example 256, 512 and 1,024 tokens, or fixed-size against heading-based.
For each setting, retrieve the top 5 chunks per question and check whether the answer phrase appears in any of them. The share of questions where it does is the hit rate at 5. Also record the total tokens the top 5 chunks would add to a prompt, because larger chunks cost more on every call.
Pick the smallest setting with a good hit rate, then read the questions it still misses. Misses often point to parsing problems, like a table that came out as noise, rather than chunk size.
- 30 to 50 questions with a known answer phrase
- Metric: hit rate at k
- Track prompt tokens per setting
- Read the misses: often a parsing problem
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Parse PDFs and HTML into text~45m
- 2Chunk by size with overlap~45m
- 3Chunk by structure and headings~45m
- 4Compare retrieval across chunk sizes~45m
Key points
- Too large and chunks are vague; too small and they lose context.
- A few hundred tokens with some overlap is a common starting point.
- Keep the section title and source with each chunk as metadata.
- Clean parsing matters; garbage text from PDFs gives garbage retrieval.
- Compare chunk sizes on real questions instead of guessing.
Key terms
Tap a card to flip it. 0/4 known
Examples
def chunk_words(text: str, size: int = 200, overlap: int = 40) -> list[str]:
words = text.split()
step = size - overlap
return [
' '.join(words[i:i + size])
for i in range(0, max(len(words) - overlap, 1), step)
]
doc = 'word ' * 500
chunks = chunk_words(doc)
print(len(chunks), [len(c.split()) for c in chunks])Fixed-size word chunks with overlap.
Splitting Markdown by headings with a context header
Your help centre is written in Markdown. Step 1: read the file line by line. Step 2: when a heading appears, close the current chunk and update the heading path, trimming it to the heading's level so a new ## replaces the old one. Step 3: start every chunk's text with its heading path, such as Billing > Refunds, so the embedding knows what the chunk is about. Step 4: keep the section path as metadata for filtering and citations. Long sections can then be split further by size.
import re
def split_by_headings(md: str) -> list[dict[str, str]]:
chunks, path, buf = [], [], []
def flush():
if "".join(buf).strip():
section = " > ".join(path)
chunks.append({"section": section, "text": section + "\n" + "\n".join(buf).strip()})
buf.clear()
for line in md.splitlines():
if m := re.match(r"^(#{1,6})\s+(.*)", line):
flush()
path[:] = path[: len(m.group(1)) - 1] + [m.group(2).strip()]
else:
buf.append(line)
flush()
return chunksTesting three chunk sizes
You must choose a chunk size for 400 product manuals. Step 1: write 40 questions, each with a short answer phrase copied from the manual. Step 2: build three indexes with 256, 512 and 1,024 token chunks and about 12% overlap. Step 3: for each, count how often the answer phrase appears in the top 5 chunks. Step 4: print the hit rate next to the prompt tokens the top 5 would add. build_index, docs and questions are your own code and data.
def hit_rate(questions: list[dict], search, k: int = 5) -> float:
hits = 0
for q in questions:
chunks = search(q["question"], k)
hits += any(q["answer_phrase"] in c for c in chunks)
return hits / len(questions)
for size in (256, 512, 1024):
index = build_index(docs, chunk_tokens=size, overlap_tokens=size // 8)
rate = hit_rate(questions, index.search)
print(f"{size:>5} tokens: hit@5 = {rate:.0%}, prompt adds ~{5 * size} tokens")Quick reference
- Read the extracted text of a few real documents before indexing anything
- Measure chunk size in tokens; stay under the embedding model's max input
- Start around 200 to 800 tokens with 10 to 20% overlap, then test
- Split at headings first, then by size inside long sections
- Prepend the title and heading path to each chunk before embedding
- Store source, page and section path as metadata for filters and citations
- Compare settings by hit rate at k on 30 to 50 real questions
Common mistakes
- Indexing headers, footers and page numbers as content.
- Picking a chunk size once and never testing alternatives.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Extract text from a PDF with pypdf, print the first 1,000 characters of three pages, and list the junk you see (headers, page numbers, broken words).
- Exercise 2medium
Write a function that removes lines repeated on more than half of the pages (headers and footers) from a list of page texts.
- Exercise 3hard
Implement a token-based chunker with overlap that never cuts inside a sentence: build chunks from whole sentences up to max_tokens, and start each new chunk with the last sentences that fit in overlap_tokens.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the best chunk size for RAG?
- There is no universal best. A few hundred tokens with some overlap is a good start; test two or three sizes on your own questions and keep the smallest that retrieves well.
- Should I use a library like LangChain or LlamaIndex for chunking?
- Their splitters are handy and well tested, especially the recursive ones. Still read the output, and make sure sizes are measured in tokens for your embedding model.
- How do I handle tables in documents?
- Extract them with a table-aware tool, keep each table whole in one chunk if it fits, and add a short description or the column headers so the chunk is understandable on its own.