Document ingestion & parsing

In one sentence

Turn messy PDFs, slides, scans and web pages into clean, structured text with metadata before chunking; most RAG quality problems start here, not in the model.

Analogy: Handing a brilliant analyst a report that went through a shredder and was taped back out of order: the analysis can only be as good as the pages they can read.

Route by document type, normalize everything to Markdown with source, date and ACL attached, and gate on a quality check before chunking.

How it works

  • Keep the structure (headings, lists, tables, reading order) and metadata (source, date, author, permissions) of every file.
  • Naive PDF extraction interleaves two-column layouts, flattens tables into loose cells, and repeats headers and footers.
  • Scans need OCR: under ~100–200 extracted characters per page usually means there is no text layer.
  • Options span plain extractors, layout-aware parsers and vision LLMs: best on complex layouts, but slower, pricier, can hallucinate.
  • Emit Markdown with headings and tables intact, and copy the ACL into every chunk for permission checks.

Check yourself

Answer to mark it learned; your answers aren't scored.

After ingesting 10,000 PDFs, a few hundred documents never show up in any search result. Their parsed output averages ~40 characters per page. Most likely cause and fix?

Go deeper

Full explanation

Parsing converts source files into text the rest of the pipeline can use, keeping structure (headings, lists, tables, reading order) and metadata (source, title, date, author, permissions). It is unglamorous and it is where most RAG effort goes: garbage in, garbage out.

What breaks:

  • PDFs store glyphs at coordinates, not paragraphs. Naive extraction interleaves two-column layouts and repeats headers, footers and page numbers on every page.
  • Tables flattened to a stream of cells lose which number belongs to which row and column.
  • Scans and photos have no text layer: they need OCR.
  • Slides are fragments; the meaning sits in charts and speaker notes.
  • HTML is mostly boilerplate: navigation, cookie banners, footers.

Tooling, cheapest to richest: plain text extractors (pypdf, PyMuPDF); layout-aware open-source parsers (Unstructured, Docling); managed services (Azure AI Document Intelligence, AWS Textract, LlamaParse); and vision LLMs that read page images directly — best on complex layouts, but slower, pricier and able to hallucinate text.

Emit Markdown with headings and tables preserved so Chunking strategies can split on structure, and copy the ACL into every chunk for Metadata filters & permission-aware retrieval.

Code Parse a PDF to Markdown with Docling, keep metadata
pythonParse a PDF to Markdown with Docling, keep metadata
from pathlib import Path
from docling.document_converter import DocumentConverter

converter = DocumentConverter()  # layout model + table structure + OCR

def parse(path: Path, acl: list[str]) -> dict:
    doc = converter.convert(path).document
    md = doc.export_to_markdown()  # headings as #, tables as Markdown tables

    # Cheap quality gate: almost no text per page usually means a scan OCR missed
    chars_per_page = len(md) / max(len(doc.pages), 1)
    if chars_per_page < 200:
        raise ValueError(f"{path.name}: {chars_per_page:.0f} chars/page, send to review")

    return {
        "text": md,
        "source": str(path),
        "modified": path.stat().st_mtime,  # enables freshness filters later
        "acl": acl,  # copied into every chunk for permission filtering
    }
Real example

A bank indexes 3,000 annual-report PDFs with pypdf. Users ask "What was the 2023 net interest margin?" and get wrong figures: two-column pages came out with sentences interleaved, and the financial tables became a flat run of numbers with no row labels. Switching to a layout-aware parser that emits tables as Markdown, and dropping repeated headers and footers, fixes most of it — with no change to embeddings, prompt or model. The scanned pages go to OCR, and any page under 200 characters is flagged for review.

Trade-offs +3 · −3

+ You gain

  • Fixing parsing often helps more than swapping the embedding model or the LLM.
  • Preserved structure enables structure-aware chunking and precise citations (section, page).
  • Metadata captured here powers filters, freshness and access control downstream.

− You pay

  • Layout models and OCR are far slower than text extraction; large backlogs need GPUs or a paid API.
  • Vision-LLM parsing can hallucinate or silently drop text.
  • No parser wins on every format, so you end up routing by document type.

Use it when

Always: every RAG pipeline has this step. Invest more when sources are PDFs with tables, multi-column layouts, scans or slides, or when answers depend on exact numbers.

Avoid it when

Skip heavy layout models for clean Markdown, plain HTML docs or DOCX with real heading styles: a simple converter is faster, cheaper and deterministic.

Numbers to know 3
  • Managed OCR lists at ~$1.50 per 1,000 pages; layout or table extraction ~$10–15 per 1,000 (Azure, AWS list prices, 2026).
  • Under ~100–200 extracted characters per page usually means a scan that needs OCR.
  • Read 20–50 parsed documents by eye before tuning anything downstream.
Common pitfalls 4
  • Never inspecting the output: teams tune retrieval for weeks on text that is already scrambled.
  • Dropping source, date and permissions at parse time — you can't filter or cite later.
  • Keeping repeated headers, footers and legal disclaimers: they pollute every chunk's embedding.
  • Re-parsing the whole corpus on every run instead of hashing files and re-processing only changes.
Interview questions 2

Answer out loud first, then reveal.

Your RAG over PDFs returns wrong numbers from financial tables. What do you do?Show answer

I look at the parsed output before touching the model. Naive extractors usually turn tables into a flat sequence of numbers with no row or column labels, so the retriever can't match them and the LLM can't read them. I'd switch to a layout-aware parser that exports tables as Markdown or HTML, keep each table with its caption and section heading in one chunk, and for wide tables also index one line per row, like "2023 · net interest margin · value". Then I add eval questions that target table values specifically.

Open-source parser, managed service or vision LLM: how do you choose?Show answer

By document mix, volume and risk. I sample ~50 representative documents and score each option on structure fidelity and text accuracy. Clean digital PDFs and DOCX: open source like Docling or Unstructured, self-hosted, deterministic and cheap. Scans, forms and dense tables: a managed service like Azure Document Intelligence or Textract, priced per page. Vision LLMs for the hardest layouts, such as charts and diagrams, but I verify them against the text layer because they can hallucinate. In practice I route by document type rather than pick a single tool.