Search Tutorials
--Ads--Handling Large Documents in RAG
Strategies for books, long reports and huge PDFs: streaming extraction, hierarchy, summaries and limits.
A 600-page manual, a 300-page annual report or a whole book causes problems that small files do not. Loading it at once can exhaust memory, one parsing error can lose the entire document, chunks lose track of which chapter they came from, and questions like "summarise chapter 4" cannot be answered from a few retrieved chunks. This lesson covers practical strategies for large documents: streaming extraction, keeping the document hierarchy, parallel processing, and hierarchical summaries.
What you will learn
- How to extract large PDFs page by page with bounded memory
- How to keep chapter and section context on every chunk using the table of contents
- How to process big documents in parallel and resume after failures
- How to answer document-level questions with hierarchical summaries
Prerequisites
Installation
pip install pymupdf anthropic sentence-transformers
What goes wrong with large documents
| Problem | Symptom | Strategy |
|---|---|---|
| Memory | The process is killed while loading a huge file | Stream page by page; write results as you go |
| Fragility | One bad page fails the whole document | Handle errors per page; record and continue |
| Lost context | A chunk says "the limit is 5%" without saying which product | Attach chapter and section titles to each chunk |
| Slow ingestion | Hours to parse one book | Parallelise across page ranges; resume from checkpoints |
| Broad questions | "What are the main risks in this report?" retrieves random fragments | Section and document summaries as extra retrieval units |
Step 1: Stream pages and keep the hierarchy
PyMuPDF reads one page at a time, and many PDFs include a table of contents (bookmarks) that gives the chapter structure. get_toc() returns entries of [level, title, page] with 1-based page numbers. We use it to label every page with its section path:
import json
from pathlib import Path
import fitz # PyMuPDF
def section_paths(doc: fitz.Document) -> dict[int, str]:
"""Map each 1-based page number to a path like 'Part II > 4 Risk Management > 4.2 Credit Risk'."""
toc = doc.get_toc() # [[level, title, page], ...]; empty if no bookmarks
paths, stack, current = {}, [], ""
entries = sorted(toc, key=lambda e: e[2])
i = 0
for page in range(1, doc.page_count + 1):
while i < len(entries) and entries[i][2] <= page:
level, title, _ = entries[i]
stack = stack[:level - 1] + [title.strip()]
current = " > ".join(stack)
i += 1
paths[page] = current
return paths
def extract_pages(pdf_path: str, out_path: str) -> None:
"""Write one JSON line per page, so memory stays flat and progress is saved."""
with fitz.open(pdf_path) as doc, open(out_path, "w", encoding="utf-8") as out:
paths = section_paths(doc)
for page_number in range(1, doc.page_count + 1):
try:
text = doc.load_page(page_number - 1).get_text("text")
except Exception as error: # damaged page: record it and carry on
print(f"page {page_number}: {error}")
continue
if text.strip():
out.write(json.dumps({"page": page_number, "section": paths[page_number],
"text": text}) + "\n")
extract_pages("annual-report-2026.pdf", "annual-report-2026.pages.jsonl")
If a PDF has no bookmarks, detect headings from font sizes (the layout-aware parsers in Layout-Aware Parsers do this), or fall back to page numbers only.
Step 2: Chunk with context
Chunk within each section, never across a chapter boundary, and put the section path at the start of the chunk text so that both the embedding and the model see it:
from itertools import groupby
def chunk_pages(pages_path: str, source: str, max_words: int = 300, overlap: int = 50) -> list[dict]:
pages = [json.loads(line) for line in open(pages_path, encoding="utf-8")]
chunks = []
for section, group in groupby(pages, key=lambda p: p["section"]):
group = list(group)
words, page_of_word = [], []
for p in group:
for w in p["text"].split():
words.append(w)
page_of_word.append(p["page"])
step = max_words - overlap
for start in range(0, max(len(words) - overlap, 1), step):
end = min(start + max_words, len(words))
chunks.append({
"text": f"[{section}]\n" + " ".join(words[start:end]) if section else " ".join(words[start:end]),
"metadata": {"source": source, "section": section,
"page_start": page_of_word[start], "page_end": page_of_word[end - 1]},
})
return chunks
chunks = chunk_pages("annual-report-2026.pages.jsonl", "annual-report-2026.pdf")
print(len(chunks), chunks[100]["metadata"])
1184 {'source': 'annual-report-2026.pdf', 'section': 'Part II > 4 Risk Management > 4.2 Credit Risk', 'page_start': 87, 'page_end': 88}
Page ranges in the metadata let answers cite "pages 87–88", which users find very helpful in long documents.
Step 3: Parallelise and resume
Text extraction is CPU-bound, so split very large files into page ranges and process them in separate processes. Each worker writes its own output file, which doubles as a checkpoint: if a run fails, finished ranges are skipped next time.
from concurrent.futures import ProcessPoolExecutor
def extract_range(args: tuple[str, int, int, str]) -> str:
pdf_path, first, last, out_path = args
if Path(out_path).exists():
return out_path # done in an earlier run
tmp = out_path + ".tmp"
with fitz.open(pdf_path) as doc, open(tmp, "w", encoding="utf-8") as out:
for page_number in range(first, last + 1):
text = doc.load_page(page_number - 1).get_text("text")
out.write(json.dumps({"page": page_number, "text": text}) + "\n")
Path(tmp).rename(out_path) # only complete files count as done
return out_path
def parallel_extract(pdf_path: str, pages_per_job: int = 100, workers: int = 4) -> list[str]:
with fitz.open(pdf_path) as doc:
total = doc.page_count
jobs = [(pdf_path, start, min(start + pages_per_job - 1, total), f"{pdf_path}.{start:05d}.jsonl")
for start in range(1, total + 1, pages_per_job)]
with ProcessPoolExecutor(max_workers=workers) as pool:
return list(pool.map(extract_range, jobs))
if __name__ == "__main__": # required for multiprocessing on Windows
print(parallel_extract("manual.pdf"))
Add the section paths afterwards with section_paths, which only reads the table of contents. Embedding is usually the slower step for big collections; batch it as in Embedding Cost and Batching.
Step 4: Hierarchical summaries for broad questions
Retrieval of small chunks works well for specific questions but poorly for "What are the main themes of chapter 4?". Add summary chunks at section and document level and index them alongside the normal chunks:
from rag_helpers import ask
def summarise_sections(chunks: list[dict], max_words_in: int = 6000) -> list[dict]:
summaries = []
for section, group in groupby(chunks, key=lambda c: c["metadata"]["section"]):
text = " ".join(c["text"] for c in group).split()[:max_words_in]
summary = ask("Summarise this section of a long document in 5-8 sentences. Keep key numbers, "
f"names and conclusions.\n\nSection: {section}\n\n{' '.join(text)}", max_tokens=600)
summaries.append({"text": f"[Summary of {section}]\n{summary}",
"metadata": {"source": chunks[0]["metadata"]["source"], "section": section,
"kind": "section_summary"}})
return summaries
section_summaries = summarise_sections(chunks)
document_summary = ask("Combine these section summaries into a one-page summary of the whole document:\n\n"
+ "\n\n".join(s["text"] for s in section_summaries), max_tokens=1200)
At query time, a router (or simply the retriever) can prefer summary chunks for broad questions and detailed chunks for specific ones. This is the idea behind RAPTOR-style hierarchical indexes (RAPTOR: Recursive Summarization Trees). Summaries cost one model call per section, so generate them once at ingestion and regenerate only for changed sections.
When to use the long context window instead
Modern models accept very long inputs (see Long-Context Models vs RAG). For a one-off question about a single long document, sending large parts of it directly can be simpler than RAG. For many users, many documents, repeated questions, citations and access control, a RAG index stays cheaper and faster. A common hybrid: retrieve the most relevant sections with RAG, then send those whole sections (not just chunks) to the model.
Common errors and troubleshooting
- Memory grows during ingestion: you are collecting all pages or chunks in lists; write them to disk or the index as you go.
- Empty text from scanned pages: those pages need OCR (see Parsing Complex Documents).
- Wrong sections: bookmarks can point to the wrong page; spot-check a few section paths against the document.
- Multiprocessing hangs on Windows: put the entry point under
if __name__ == "__main__":.
Key takeaways
- Stream large documents page by page, handle errors per page and write results as you go.
- Use the table of contents to attach section paths and page ranges to every chunk.
- Parallelise extraction by page range with file-based checkpoints.
- Add section and document summaries to answer broad questions.
Frequently asked questions
What chunk size should I use for long documents?
The same principles apply as for any document (see Evaluating Chunking Strategies); what changes is that context (section paths) and parent-child retrieval become more valuable.
Should a book be one document or many?
Keep one document id for updates and deletion, but treat chapters as units for chunking, summaries and filters.
Practice exercises
- Index a long PDF with and without section paths in chunk text, and compare retrieval on ten questions.
- Add a "summarise chapter N" route that retrieves only
section_summarychunks for that chapter.