Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Retrieval (RAG)AI guideIntermediate#rag#ingestion#parsing#ocr
Frame · ai-engineering / rag / 02-document-parsing-and-ingestion.mdGuide 014 / 103

Document parsing and ingestion

Most RAG failures I have debugged were not retrieval problems at all. The answer was in the source PDF, but the parser had turned a pricing table into a word salad or dropped the scanned appendix entirely. Parsing is the least glamorous step in the pipeline and the one with the highest leverage. This doc covers how modern parsers work, how to pick one, and when to skip text extraction altogether and retrieve page images.

Why it matters

Everything downstream inherits the parser's mistakes. If reading order is wrong, chunks mix two columns into nonsense sentences. If headings are lost, you cannot chunk by section or attach a breadcrumb like "Policy > Leave > Carry-over". If a table is flattened into a stream of numbers, no embedding model will recover which number belonged to which row. And if scanned pages produce no text, those pages are simply invisible to search.

Enterprise corpora are full of exactly the hard cases: two-column reports, PDFs exported from slides, scanned contracts with stamps, spreadsheets saved as PDF, and forms. Plain text extraction (the kind you get from a basic PDF library) reads the character stream in whatever order the PDF happens to store it, which is often not the order a human reads.

How it works

A layout-aware parser treats each page as an image plus (when available) an embedded text layer, and runs several stages:

  1. Text layer extraction for born-digital PDFs, which is fast and exact.
  2. OCR for scanned pages or images with no text layer.
  3. Layout analysis: a vision model detects regions such as title, paragraph, list, table, figure, header and footer.
  4. Reading order reconstruction across columns and regions.
  5. Table structure recognition: rows, columns, header cells and spans.
  6. Export to a structured format (Markdown, HTML or JSON) that keeps headings, tables and page numbers.

Open-source and hosted tools package these stages differently:

  • Docling (originally from IBM Research, MIT licensed) runs locally, uses a layout model and the TableFormer model for table structure, and exports Markdown or JSON. It also ships a structure-aware chunker.
  • Unstructured offers partitioning strategies: fast (rule-based text extraction), hi_res (model-based layout detection), ocr_only, auto, and in newer releases a vlm strategy that uses a vision language model. Its docs are explicit that fast treats table cells as a mix of title, list and text elements, so use a model-based strategy when tables matter.
  • LlamaParse is a hosted parser with modes ranging from a fast mode without LLM post-processing to LLM and vision-model based modes, plus an auto mode that chooses per page.
Rendering diagram…

The vision alternative

There is a second family of approaches that skips text extraction. The ColPali paper (ICLR 2025) embeds page images directly with a vision language model and produces multi-vector embeddings that are matched with ColBERT-style late interaction. The authors argue that text extraction pipelines are slow and fragile and miss visual cues, and they introduce the ViDoRe benchmark for visually rich document retrieval. In practice this is attractive for slide decks, infographics, charts and forms where layout carries meaning. You then send the retrieved page images to a multimodal model to generate the answer. The cost is larger indexes (many vectors per page) and less control over citing a specific sentence.

Reference architecture

A production ingestion service is a queue-driven pipeline, not a script. Files arrive from connectors, get parsed by the right engine, and are written to the index idempotently so re-runs do not create duplicates.

Rendering diagram…

Two details from that diagram are worth calling out. First, store the raw parse output separately from the index (the "raw parse store"). When you change chunking or embeddings later, you can rebuild without re-running expensive OCR. Second, compute a content hash per document so unchanged files are skipped and changed files replace their old chunks cleanly.

Code

Docling in Python: convert a PDF, export Markdown, then use its structure-aware chunker, which keeps heading context with each chunk.

from docling.document_converter import DocumentConverter
from docling.chunking import HybridChunker

converter = DocumentConverter()
result = converter.convert("reports/annual-report-2025.pdf")
doc = result.document

# Full Markdown for the raw parse store
markdown = doc.export_to_markdown()
with open("parsed/annual-report-2025.md", "w") as f:
    f.write(markdown)

# Structure-aware chunks, each with its heading path
chunker = HybridChunker()
records = []
for i, chunk in enumerate(chunker.chunk(dl_doc=doc)):
    records.append({
        "chunk_id": f"annual-report-2025:{i}",
        "text": chunker.contextualize(chunk=chunk),  # prepends headings
        "source": "annual-report-2025.pdf",
    })

print(len(records), records[0]["text"][:300])

The contextualize call is the quiet win here: it prefixes each chunk with the headings above it, so a chunk that only says "carry over up to 10 days" also carries "Leave policy > Vacation" into the embedding.

Trade-offs and pitfalls

  • Speed versus fidelity. Model-based layout and OCR are much slower than text-layer extraction. Route by document type instead of running the heaviest parser on everything.
  • Tables need a policy. Decide whether a table becomes a Markdown table inside a chunk, a chunk of its own, or one chunk per row with the header repeated. Row-level chunks work well for lookup questions; whole-table chunks work better for comparisons.
  • Headers and footers pollute retrieval. A footer like "Confidential, page 7 of 92" repeated on every page creates near-duplicate noise. Strip them.
  • OCR errors are silent. A misread "0" as "O" breaks keyword search on part numbers. Spot-check OCR output on a sample of each document family.
  • Images and charts carry facts. If a chart holds the answer, text extraction will not find it. Either caption figures with a vision model at ingestion time or use page-image retrieval for those collections.
  • Hosted parsers move data. Sending regulated documents to a third-party API may be a compliance issue. Local tools like Docling exist partly for this reason.
  • Parsers change. Pin versions and re-run a parsing regression set before upgrading, because a new layout model can change chunk boundaries across the whole corpus.

Checklist

  • Classify your corpus by document family (digital PDF, scans, slides, spreadsheets, HTML) and route each to a suitable parser.
  • Preserve headings, reading order, tables and page numbers in a structured intermediate format.
  • Store raw parse output separately so you can re-chunk without re-parsing.
  • Strip repeated headers, footers and boilerplate before chunking.
  • Pick an explicit table strategy and test it with real lookup questions.
  • Hash documents for idempotent, incremental re-ingestion and clean deletes.
  • Consider page-image retrieval for visually rich collections.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.