PDF VectorPDF Vector
Back to all articles

Retrieval Pipelines for Long PDF Documents

Retrieval for 300 to 2,000-page PDFs: parsing with page numbers, section-aware chunking, tables, hierarchical and hybrid search, and page-range citations.

Retrieval Pipelines for Long PDF Documents

A retrieval pipeline for long PDF documents has to do more than a standard RAG setup. A 600-page technical manual or an annual report produces thousands of chunks, many sections share the same vocabulary, and the answer to one question can sit in three places 200 pages apart. What works at that length: parse the whole file with page numbers, rebuild the section hierarchy, chunk inside sections, treat tables as units, retrieve hierarchically (sections first, then passages), combine keyword and vector search, and cite page ranges. This article covers each stage with code. If you are building RAG over ordinary-length PDFs, start with RAG With PDFs: From Files to Answers, which covers the basic pipeline this one extends.

Why long PDFs break naive RAG

The usual pipeline (split into fixed-size chunks, embed, return the top five) is fine for a 15-page document. At 300 pages and beyond, four things change:

  1. Chunk count explodes. A 500-page report at roughly two to four chunks per page is 1,000 to 2,000 chunks for one file. The more candidates there are, the more often a chunk that only sounds relevant beats the right one.
  2. Vocabulary repeats across sections. "Limitations", "scope" and "exceptions" in a contract; "method", "results" and "discussion" in each chapter of a thesis. Pure similarity search cannot tell which section is meant.
  3. Answers span sections. "Compare the warranty terms for product lines A and C" needs evidence from two chapters. Top-k from a flat index rarely returns both.
  4. Long files are messy. Repeating headers and footers on every page, tables that continue over several pages, scanned appendices, two-column sections. Every parsing error is multiplied by the page count.

The fixes below address these in order: get clean, page-numbered text; recover structure; use structure in chunking and retrieval.

Size the problem first

Different products stress retrieval differently. Decide which one you are building before choosing an architecture:

PatternExampleWhat matters most
Interactive Q&A"Ask this manual" chatLatency, precise page citations
Analysis and synthesisBriefing from a 500-page reportRecall across sections, multi-step retrieval
MonitoringFlag new filings that mention a riskCheap ingestion, good metadata filters
Search and browseKnowledge portal over long documentsRanking quality, section-level results

Write down your document sizes, whether questions are local ("what does section 4 say about refunds?") or global ("compare liability terms across all suppliers"), your latency budget and how costly a missed clause is. Those answers decide how much of the hierarchy below you need.

Stage 1: Parse the whole file with page numbers

PDF Vector's Document Parse returns Markdown for the whole document and, with includePages: true, a pages array of { pageNumber, markdown }. Page limits depend on the tier:

TierMax pagesMax file sizeCredits per page
nano, mini, pro3040 MB1, 2, 4
max2,000500 MB8
auto (default)2,000500 MBthe tier it runs

For long documents, use auto or max; the smaller tiers reject anything over 30 pages. Cost scales with pages, so it is worth doing the arithmetic:

  • A 1,200-page scanned maintenance manual on max: 1,200 × 8 = 9,600 credits.
  • The same page count as a digital (text) PDF on auto, which a local engine reads without OCR and bills at most at the mini rate: at most 1,200 × 2 = 2,400 credits.

Parse once and store the result. Re-chunking and re-embedding from stored Markdown is cheap; re-parsing a 1,200-page file is not.

Long files take time to process, so do not hold a web request open for them. Pass a callback with your webhook URL: the API returns 202 immediately and POSTs the full result to the webhook when it is done, with an X-Pdfvector-Callback-Failed: true header if it failed. Send a documentId so you can match the callback to your record:

import os
import requests

PV_KEY = os.environ["PDFVECTOR_API_KEY"]

resp = requests.post(
    "https://global.pdfvector.com/api/document/parse",
    headers={"Authorization": f"Bearer {PV_KEY}"},
    json={
        "url": "https://files.example.com/manuals/turbine-x9.pdf",
        "model": "auto",
        "includePages": True,
        "documentId": "turbine-x9-rev7",
        "callback": {"url": "https://api.example.com/webhooks/pdfvector"},
    },
    timeout=60,
)
print(resp.status_code)  # 202: the result arrives at the webhook

Files over 2,000 pages must be split. Split on page boundaries with pypdf, upload each part to your object storage, and submit each part with a callback. Put the part's page offset in its documentId, so the webhook can shift page numbers back to the original document:

import io
from pypdf import PdfReader, PdfWriter

PART_PAGES = 2000

def submit_large_pdf(path: str, doc_id: str, upload_part) -> int:
    """upload_part(buffer, name) is your storage helper; it returns a signed URL for the part."""
    reader = PdfReader(path)
    total = len(reader.pages)
    for start in range(0, total, PART_PAGES):
        writer = PdfWriter()
        for i in range(start, min(start + PART_PAGES, total)):
            writer.add_page(reader.pages[i])
        buffer = io.BytesIO()
        writer.write(buffer)
        buffer.seek(0)
        part_url = upload_part(buffer, f"{doc_id}-from-{start + 1}.pdf")

        resp = requests.post(
            "https://global.pdfvector.com/api/document/parse",
            headers={"Authorization": f"Bearer {PV_KEY}"},
            json={
                "url": part_url,
                "model": "auto",
                "includePages": True,
                "documentId": f"{doc_id}:offset:{start}",
                "callback": {"url": "https://api.example.com/webhooks/pdfvector"},
            },
            timeout=60,
        )
        resp.raise_for_status()  # 202 per part
    return total

def pages_from_callback(payload: dict) -> tuple[str, list[dict]]:
    """In the webhook: restore original page numbers from the part's offset."""
    doc_id, _, offset = payload["documentId"].rpartition(":offset:")
    start = int(offset)
    return doc_id, [
        {"pageNumber": page["pageNumber"] + start, "markdown": page["markdown"]}
        for page in payload["pages"]
    ]

Mark the document ready once callbacks for all parts have arrived, then sort the pages by pageNumber. Each part must also stay under 500 MB; split into smaller parts if the source is very image-heavy. A synchronous multipart upload (files={"file": ...}) also works, but only suits small parts that finish within your HTTP timeout.

Stage 2: Recover the section hierarchy

Markdown headings (#, ##, ###) give you the document outline. Walk the pages in order, keep a stack of open headings, and record each section's path and page range. Remove repeating headers and footers first, or they pollute every chunk:

import re
from collections import Counter

HEADING = re.compile(r"^(#{1,6})\s+(.*)")

def strip_running_lines(pages: list[dict], threshold: float = 0.5) -> list[dict]:
    """Drop short lines that appear on more than half the pages (running headers, footers)."""
    counts = Counter()
    for p in pages:
        counts.update({line.strip() for line in p["markdown"].splitlines() if 0 < len(line.strip()) < 80 and not line.lstrip().startswith(("|", "#"))})
    running = {line for line, n in counts.items() if n > threshold * len(pages)}
    return [
        {**p, "markdown": "\n".join(l for l in p["markdown"].splitlines() if l.strip() not in running)}
        for p in pages
    ]

def build_sections(pages: list[dict]) -> list[dict]:
    sections, stack = [], []  # stack of (level, title)
    current = {"path": "(front matter)", "page_start": 1, "page_end": 1, "lines": []}
    for page in pages:
        for line in page["markdown"].splitlines():
            m = HEADING.match(line)
            if m:
                if current["lines"]:
                    sections.append(current)
                level, title = len(m.group(1)), m.group(2).strip()
                stack = [(l, t) for l, t in stack if l < level] + [(level, title)]
                current = {"path": " > ".join(t for _, t in stack), "page_start": page["pageNumber"],
                           "page_end": page["pageNumber"], "lines": []}
            else:
                current["lines"].append((page["pageNumber"], line))
                current["page_end"] = page["pageNumber"]
    if current["lines"]:
        sections.append(current)
    return sections

Two cautions. Page numbers printed in the footer ("Page 37 of 612") often differ from the PDF page index; cite the PDF page and, if users expect printed numbers, store both. And the 50% threshold can remove a legitimate line that genuinely repeats; check the running set on a few documents before trusting it.

If a document has few or no headings (scanned contracts are common offenders), fall back to fixed page windows (for example five pages per "section") so the hierarchy below still works.

Stage 3: Chunk inside sections

With sections in hand, chunk within each section and never across a section boundary. Each chunk records its section path and the first and last page it covers:

def split_paragraphs(lines: list[tuple[int, str]]) -> list[list[tuple[int, str]]]:
    """Group (page, line) pairs into paragraphs; a Markdown table always forms its own paragraph."""
    paragraphs, current = [], []
    for page, line in lines:
        if not line.strip():
            if current:
                paragraphs.append(current)
                current = []
            continue
        starts_table = line.lstrip().startswith("|")
        if current and starts_table != current[-1][1].lstrip().startswith("|"):
            paragraphs.append(current)  # text -> table or table -> text boundary
            current = []
        current.append((page, line))
    if current:
        paragraphs.append(current)
    return paragraphs

def is_table(paragraph) -> bool:
    return all(line.lstrip().startswith("|") for _, line in paragraph)

def chunk_sections(sections: list[dict], doc_id: str, max_chars: int = 1800) -> list[dict]:
    chunks = []
    for s_index, section in enumerate(sections):
        groups, current, size = [], [], 0
        for para in split_paragraphs(section["lines"]):
            length = sum(len(line) for _, line in para)
            if current and size + length > max_chars:
                groups.append(current)
                current, size = [], 0
            current.append(para)
            size += length
        if current:
            groups.append(current)

        for seq, group in enumerate(groups):
            chunks.append({
                "doc_id": doc_id,
                "section": s_index,
                "seq": seq,
                "path": section["path"],
                "page_start": group[0][0][0],
                "page_end": group[-1][-1][0],
                "kind": "table" if all(is_table(p) for p in group) else "text",
                "content": "\n\n".join("\n".join(line for _, line in p) for p in group),
            })
    return chunks

The chunker packs whole paragraphs up to the size limit and never cuts inside a paragraph or a table; a chunk can span a page break inside its section, which is why it stores both page_start and page_end. A single paragraph or table longer than the limit becomes one oversized chunk (see Stage 4 for splitting long tables). When you embed a chunk, prefix it with the section path ("4 Maintenance > 4.3 Bearings > Lubrication intervals"); in long documents the path often carries more meaning than the chunk text itself.

Stage 4: Handle tables as first-class content

Long technical and financial documents keep much of their substance in tables. Three rules:

  • Keep a table whole when it fits, and mark it kind = 'table' so you can boost or filter tables for numeric questions.
  • Split long tables by rows and repeat the header row in every piece. A row without its header ("| 3.2 | 140 | 0.8 |") is meaningless to both the embedding model and the LLM.
  • Embed a short description with the table. Combine the section path, any caption line above the table and the header row ("Table: lubrication intervals by bearing type; columns: bearing, interval (hours), grease grade"). Numbers alone embed poorly.

Parsing quality decides whether this works at all: tables that continue over page breaks, merged cells and rotated pages are where simple extractors fail. On max, the parse response also includes an html field, which preserves merged cells that Markdown tables cannot express. For turning tables into structured data rather than retrieval chunks, see Convert PDF Tables to JSON.

Stage 5: Retrieve hierarchically

Hierarchical retrieval narrows the search the way a person uses a table of contents: find the right sections first, then the right passages inside them.

  1. Section level. For each section, store a short representation: its path plus a summary. A summary can be generated by an LLM once at ingestion, or, cheaply, be the path plus the first 500 characters. Embed these.
  2. Passage level. Search chunks only within the top sections from step 1.
  3. Neighbour expansion. Add the chunk before and after each hit from the same section, so an answer that starts at the end of one chunk is not cut off.

Postgres with pgvector handles both levels plus keyword search in one database:

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE sections (
  id          bigserial PRIMARY KEY,
  doc_id      text NOT NULL,
  path        text NOT NULL,
  page_start  int  NOT NULL,
  page_end    int  NOT NULL,
  summary     text NOT NULL,
  embedding   vector(1536) NOT NULL
);

CREATE TABLE chunks (
  id          bigserial PRIMARY KEY,
  doc_id      text NOT NULL,
  section_id  bigint NOT NULL REFERENCES sections(id),
  seq         int  NOT NULL,
  page_start  int  NOT NULL,
  page_end    int  NOT NULL,
  kind        text NOT NULL DEFAULT 'text',
  content     text NOT NULL,
  embedding   vector(1536) NOT NULL,
  tsv         tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED
);

CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON chunks USING gin (tsv);
CREATE INDEX ON chunks (doc_id, section_id, seq);

The vector dimension must match your embedding model (1536 fits OpenAI's text-embedding-3-small, for example). Within a single document, scanning a few thousand chunk vectors exactly is fast; the HNSW index matters when you search across many documents.

Stage 6: Combine keyword and vector search

Vector search handles paraphrase; keyword search handles exact strings that long documents are full of: clause numbers, part numbers, defined terms, error codes. Run both and merge the rankings with reciprocal rank fusion (RRF), which needs no score calibration. This query does hierarchical vector search inside the top sections, keyword search across the whole document (so an exact term can rescue a section the summaries missed), and fuses the two:

-- $1 = doc_id, $2 = query embedding, $3 = the user's question as text
WITH top_sections AS (
  SELECT id FROM sections
  WHERE doc_id = $1
  ORDER BY embedding <=> $2
  LIMIT 5
),
semantic AS (
  SELECT c.id, row_number() OVER (ORDER BY c.embedding <=> $2) AS r
  FROM chunks c
  WHERE c.section_id IN (SELECT id FROM top_sections)
  ORDER BY c.embedding <=> $2
  LIMIT 40
),
lexical AS (
  SELECT c.id, row_number() OVER (ORDER BY ts_rank_cd(c.tsv, q) DESC) AS r
  FROM chunks c, websearch_to_tsquery('english', $3) AS q
  WHERE c.doc_id = $1 AND c.tsv @@ q
  ORDER BY ts_rank_cd(c.tsv, q) DESC
  LIMIT 40
),
fused AS (
  SELECT id, sum(1.0 / (60 + r)) AS score
  FROM (SELECT id, r FROM semantic UNION ALL SELECT id, r FROM lexical) AS ranked
  GROUP BY id
)
SELECT c.id, c.section_id, c.seq, c.page_start, c.page_end, c.kind, c.content, s.path, f.score
FROM fused f
JOIN chunks c   ON c.id = f.id
JOIN sections s ON s.id = c.section_id
ORDER BY f.score DESC
LIMIT 8;

In Python, the pgvector package registers the vector type with psycopg (from pgvector.psycopg import register_vector), so you can pass a NumPy array as $2 (written %s in psycopg). For the neighbour expansion, fetch seq - 1 and seq + 1 for each hit's section_id.

Stage 7: Assemble context and cite page ranges

Order the final passages by position in the document, not by score; the model reads a coherent sequence better than a shuffled one. Label each passage with its section path and page range, and require citations in that form:

[4 Maintenance > 4.3 Bearings, pp. 212-213]
| Bearing | Interval (hours) | Grease |
|---|---|---|
...

[9 Warranty > 9.2 Exclusions, p. 588]
Damage caused by lubrication outside the intervals in section 4.3 ...

For questions that span the document ("compare", "list all", "summarize every chapter"), single-shot retrieval is not enough. Two patterns help:

  • Query decomposition. Ask the LLM to split the question into sub-questions ("warranty terms for line A", "warranty terms for line C"), retrieve for each, then answer from the union.
  • Map-reduce over sections. For "list every X", run a cheap per-section pass over candidate sections found by keyword search, then combine the findings. It costs more but does not depend on top-k luck.

As in the shorter pipeline, verify after generation that every cited section and page range was in the context you sent, and link each citation to the PDF page.

Evaluate where long documents fail

Build an evaluation set that reflects length, not just topic:

  • Depth. Questions whose answers sit on pages near the start, middle and end. Retrieval that only works on the first 50 pages is a common bug (truncated parsing, front-loaded summaries).
  • Exact terms. Questions that use clause numbers, part numbers or defined terms. These test the keyword side.
  • Tables. Questions answerable only from a table cell.
  • Multi-section questions. Answers needing two or more sections.
  • Absent answers. Questions the document does not answer. The system should say so rather than cite something close.

Track section hit rate (the right section in the top five) and passage hit rate (the right page in the final context) separately. When section hit rate is low, improve section summaries or headings; when passage hit rate is low inside the right section, improve chunking or add keyword search.

Cost and latency

  • Parsing is a one-time cost per document version: pages × the tier's per-page credits, as computed in Stage 1. Store the Markdown.
  • Embedding is also one-time, and roughly proportional to the document's text length; section summaries add one LLM call per section if you generate them.
  • Query time is dominated by the LLM call. Hierarchical retrieval keeps the context small (eight passages rather than thirty), which lowers both latency and token cost.
  • Re-processing. When a new revision of a manual arrives, re-parse it as a new version and keep the old one filterable, rather than overwriting it, so answers can state which revision they are based on.

For the ingestion side at platform scale (queues, retries, idempotency and multi-tenant storage), see Document Processing Architecture for SaaS. For scanned material inside long files, OCR vs Text Extraction explains what changes when pages are images.

FAQ

What is the maximum PDF length PDF Vector can parse?

2,000 pages and 500 MB per file on the max and auto tiers. The nano, mini and pro tiers accept up to 30 pages and 40 MB. Split longer files on page boundaries and add each part's page offset back.

How should I chunk a 500-page PDF?

Recover the section hierarchy from headings, chunk within sections at paragraph boundaries, keep tables whole (or split by rows with the header repeated), and store the section path and page range with every chunk.

What is hierarchical retrieval?

Searching in two stages: first find the most relevant sections using section-level summaries or embeddings, then search passages only inside those sections, optionally adding neighbouring chunks for context.

Do I need hybrid search for long documents?

Usually yes. Long documents contain many exact identifiers (clause numbers, part numbers, defined terms) that vector search handles poorly. Combining keyword and vector rankings, for example with reciprocal rank fusion, fixes most of those misses.

How do I cite pages in answers from long PDFs?

Parse with page-separated output (includePages: true), carry page_start and page_end into every chunk, label passages with section path and page range in the prompt, and verify each citation against the passages you sent.

How much does it cost to parse a 1,000-page PDF?

It depends on the tier that runs: on max, 1,000 × 8 = 8,000 credits. A digital PDF on auto that is read without OCR is billed at most at the mini rate, 1,000 × 2 = 2,000 credits. See pricing for plan sizes.