Document Ingestion, Parsing and Chunking

Retrieval can only find what ingestion preserved. Parse carefully, cut along meaning, keep the labels and make every run repeatable.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Ingestion turns files and records into searchable chunks with metadata. Parse the layout so that headings, tables and reading order survive. Cut along document structure where it exists, keep each chunk understandable on its own, attach source, version and access rules, and make the pipeline idempotent so that updates and deletions are safe. Check the output by eye and by retrieval tests.

What you will learn: the pipeline stages, parsing and layout-aware extraction, four chunking strategies, chunk size and overlap, metadata, incremental updates and quality checks.
Prerequisites: RAG Explained and Agentic RAG. The code uses only the Python standard library.

Beginner From files to chunks

The ingestion pipeline

A retrieval system never reads your documents the way you do. It reads whatever text your pipeline extracted, cut into the pieces your pipeline chose. If a table became a jumble of numbers or a sentence was split from its heading, no clever search will repair it later.

Collectconnectors, change feeds
Parsetext, layout, tables, images
Cleanheaders, duplicates, secrets
Chunkcoherent pieces
Enrichmetadata, context
Indexkeyword and vector
↺ Runs again whenever a source changes or is deleted
Each stage should keep its output so that you can inspect and replay it.

Collecting documents

Begin with a short list of sources that people trust, not with everything you can reach. For each, record an owner, how changes and deletions are detected, which access rules apply and how fresh the copy must be. Prefer change notifications or modification markers over copying everything nightly. Archive the original file with a hash, so any chunk can be traced back to exact bytes.

Parsing and layout-aware extraction

FormatCommon troubleWhat to check
HTMLMenus, banners and footers mixed into contentExtract the main content region
Word processor filesTracked changes, comments, text boxesDecide which version is authoritative
PDF with textColumns read across, broken words, repeated headersReading order and hyphenation
Scanned pagesRecognition errorsConfidence scores and sampled review
SlidesMeaning in layout and notesSlide titles, notes, diagram text
SpreadsheetsValues without headers or unitsKeep headers with rows, or query as data
Email and chatQuoted history and signaturesThread order and de-duplication

A PDF describes where marks go on a page, not what is a paragraph. Layout-aware extraction uses positions, fonts and often vision models to recover headings, columns, lists, tables, captions and footnotes. Open-source projects such as Docling, Unstructured and Apache Tika, and cloud document services, handle different mixes of formats. Compare them on your hardest pages, not on a tidy sample.

Tables and figures

  • Keep a table with its title and header row. If it must be split, repeat the headers in each part.
  • Store a structured version (rows and columns) as well as a text rendering.
  • For large numeric tables, load them into a database and query them, as in Query Rewriting, Multi-Hop, SQL and Multimodal RAG.
  • For figures, keep the caption and, if useful, a generated description marked as generated, plus a link to the image.
Parsers fail quietly

An extraction that returns empty text or nonsense usually raises no error. Flag pages with very little text, unusual symbol ratios or sudden drops in length compared with the last version, and review them.

Intermediate Chunking strategies and metadata

Why chunk at all

Search works best on focused passages, and the model should receive only what is relevant. A chunk that is too small loses meaning ("the limit is 220": which limit?). A chunk that is too large dilutes its own search signal and wastes context. The goal is a piece that answers something and makes sense alone.

StrategyHow it cutsStrengthWeakness
Fixed sizeEvery N characters or tokens, with overlapSimple and predictableSplits sentences and ideas
RecursiveBy sections, then paragraphs, then sentences until small enoughRespects natural breaksDepends on clean separators
StructuralAlong headings, clauses, functions or recordsMeaningful units with a title pathNeeds reliable structure
SemanticWhere the topic changes, judged by embedding distance or a modelWorks on unstructured proseMore cost, thresholds to tune

Compare them on one document

"""Compare three ways of cutting the same document."""
import re

DOC = """# Travel policy
## Flights
Economy is the default for all flights. Business class is allowed only for
flights longer than eight hours and needs director approval.
## Hotels
The nightly limit is 150. In capital cities the limit is 220.
## Exceptions
These limits do not apply to conference hotels booked by the events team."""

def fixed(text, size=80, overlap=10):
    flat = " ".join(text.split())
    return [flat[i:i + size] for i in range(0, len(flat), size - overlap)]

def sentences(text, per_chunk=2):
    body = " ".join(l for l in text.splitlines() if not l.startswith("#"))
    parts = re.split(r"(?<=\.)\s+", body)
    return [" ".join(parts[i:i + per_chunk]) for i in range(0, len(parts), per_chunk)]

def structural(text):
    chunks, path, lines = [], {}, []
    def flush():
        if lines:
            trail = " > ".join(path[k] for k in sorted(path))
            chunks.append(f"{trail}: {' '.join(lines)}")
            lines.clear()
    for line in text.splitlines():
        head = re.match(r"(#+)\s+(.*)", line)
        if head:
            flush()
            level = len(head[1])
            path = {k: v for k, v in path.items() if k < level}
            path[level] = head[2]
        else:
            lines.append(line.strip())
    flush()
    return chunks

NEEDS = {   # a chunk must contain all of these to answer the question
    "capital hotel limit": ["Hotels", "220"],
    "business class rule": ["eight hours", "director approval"],
}
for name, chunker in (("fixed", fixed), ("sentences", sentences),
                      ("structural", structural)):
    chunks = chunker(DOC)
    ok = [q for q, need in NEEDS.items()
          if any(all(n.lower() in c.lower() for n in need) for c in chunks)]
    print(f"{name:10} {len(chunks)} chunks, answerable: {ok}")
print()
for c in structural(DOC):
    print("-", c[:68])

Output:

fixed      5 chunks, answerable: []
sentences  3 chunks, answerable: ['business class rule']
structural 3 chunks, answerable: ['capital hotel limit', 'business class rule']

- Travel policy > Flights: Economy is the default for all flights. Bus
- Travel policy > Hotels: The nightly limit is 150. In capital cities 
- Travel policy > Exceptions: These limits do not apply to conference

The fixed cuts separate each fact from what identifies it. Sentence grouping keeps the flight rule together but drops the heading that says the limit concerns hotels. The structural version carries the heading path into each chunk, so both questions can be answered. This is one tiny document with a deliberately small size, so take the method, not the ranking: write down questions and the facts a chunk must contain, then measure.

Size and overlap

There is no universal best size. A few hundred tokens is a common starting range for prose. Overlap, often ten to twenty percent, reduces the chance of cutting an idea in half, at the price of duplicates in results. Code, contracts, FAQs and logs each have natural units that matter more than any number.

Small to search, larger to read

Parent-child retrieval indexes small passages for precise matching, then hands the model the enclosing section. Sentence-window retrieval returns the matched sentence with its neighbors. Both separate the unit of search from the unit of reading.

Metadata

FieldUsed for
Document and chunk identifiersCitations, updates, deletion
Title and heading pathContext in search and in prompts
Source, link and pageLetting people verify
Version, effective and review datesExcluding outdated material
Access list or labelsPermission filtering
Language, product, regionTargeted filters
Content hash and pipeline versionSkipping unchanged work and rebuilding

Take metadata from the source system where you can. Values guessed by a model are useful for ranking but should not decide access.

Adding context to chunks

Prefixing the title and heading path costs nothing and helps. Anthropic's contextual retrieval goes further: a model writes a short note placing each chunk within its document, and the note is prepended before embedding and keyword indexing. Anthropic reported fewer failed retrievals in its tests. It adds indexing cost, so compare against the simple heading path on your own questions.

Expert Reliable updates and quality control

Idempotent, incremental ingestion

Pipelines are rerun after failures and source changes. Running the same input twice must not create duplicates, and removed content must disappear. Give chunks stable identifiers, store a content hash and compare.

"""Idempotent ingestion: unchanged chunks are skipped, removed ones deleted."""
import hashlib

index = {}                                    # chunk_id -> record

def digest(text):
    return hashlib.sha256(text.encode()).hexdigest()[:12]

def ingest(doc_id, version, sections, acl):
    wanted = {}
    for heading, text in sections:
        chunk_id = f"{doc_id}#{heading.lower().replace(' ', '-')}"
        wanted[chunk_id] = {
            "doc": doc_id, "version": version, "heading": heading, "text": text,
            "hash": digest(heading + "\n" + text), "acl": acl}
    report = {"embedded": [], "unchanged": [], "deleted": []}
    for chunk_id, rec in wanted.items():
        old = index.get(chunk_id)
        if old and old["hash"] == rec["hash"]:
            old.update(version=version, acl=acl)    # metadata only, no new embedding
            report["unchanged"].append(chunk_id)
        else:
            index[chunk_id] = rec                   # embed here
            report["embedded"].append(chunk_id)
    for chunk_id in [c for c, r in index.items() if r["doc"] == doc_id]:
        if chunk_id not in wanted:
            del index[chunk_id]
            report["deleted"].append(chunk_id)
    return report

v1 = [("Flights", "Economy by default."), ("Hotels", "Limit 150."),
      ("Taxis", "Keep receipts.")]
v2 = [("Flights", "Economy by default."), ("Hotels", "Limit 160.")]

for version, sections in ((1, v1), (1, v1), (2, v2)):
    r = ingest("travel", version, sections, acl=["staff"])
    print(f"v{version}:", {k: [c.split("#")[1] for c in v] for k, v in r.items()})
print("index:", sorted(index))

Output:

v1: {'embedded': ['flights', 'hotels', 'taxis'], 'unchanged': [], 'deleted': []}
v1: {'embedded': [], 'unchanged': ['flights', 'hotels', 'taxis'], 'deleted': []}
v2: {'embedded': ['hotels'], 'unchanged': ['flights'], 'deleted': ['taxis']}
index: ['travel#flights', 'travel#hotels']

The second run embeds nothing. In version two only the changed section is embedded again, and the removed section is deleted. Note that permissions are refreshed even when text is unchanged, because access can change without any edit. Identifiers based on headings break if headings are renamed, so production systems often combine the source's own element identifiers with hashes.

Operational points

  • Process each document in isolation, with retries and a queue for failures.
  • Publish a new version of a document in one step, so searches never see half of it.
  • Rebuild into a new index when the parser, chunker or embedding model changes, test it, then switch.
  • Track lag from source change to searchable, and alert on it.
  • Scan for secrets and unexpected personal data before indexing.
  • Treat document text as untrusted: a file can carry instructions aimed at the model, as discussed in Supply Chain and Retrieval Poisoning.

Quality checks

CheckCatches
Random sample read by a personGarbled order, lost tables
Chunk length distributionEmpty or giant chunks
Duplicate rateRepeated boilerplate and copies
Source to chunk count reconciliationSilently skipped files
Known question setFacts that no chunk contains
Permission samplingChunks missing access labels

Fail closed on permissions: a chunk with no access information should be invisible, not public.

Content that needs its own treatment

ContentNatural unitKeep with it
Source codeFunction or classFile path, language, imports, signature
ContractsClause with sub-clausesDefinitions referenced, parties, effective date
Question and answer pagesOne question with its answerProduct and version
ManualsProcedure or step groupWarnings that precede the steps, model numbers
Meeting transcriptsTopic segmentSpeakers, times, decisions
Support ticketsProblem and confirmed resolutionStatus, product, whether the fix worked
LogsEvent windowService, time range, identifiers

Two details matter often. A warning printed before a procedure must travel with every step it governs, or the agent may recite the steps without it. A clause that uses a defined term is hard to answer from alone, so attach the definition or arrange for it to be retrieved with the clause.

Languages

Detect the language of each document and record it. Check that recognition, sentence splitting and your embedding model work for it, because tools tuned on English can cut or misread other scripts. Decide whether a question in one language should find documents in another, and test that case directly.

Versioning the pipeline

Store the parser version, chunking settings and embedding model on every chunk. When answers change after an upgrade, you can compare old and new chunks side by side, and you can rebuild only what used the faulty version.

A worked decision

Illustrative example: a policy library

A company has several hundred policies as PDFs with numbered clauses. The team first uses fixed chunks and sees answers that mix two policies. They switch to layout-aware parsing, cut by clause, prefix policy name and clause path, store effective dates and owners, and load rate tables into a database. Their question set shows which clauses are now found, and the two scanned documents that failed recognition are fixed at the source.

A first week plan

Pick twenty documents that include your messiest ones. Parse them with two tools and read the output side by side. Choose chunk boundaries by hand for three of them, then write the code that reproduces your choices. Collect thirty real questions and check, before any search is built, that each needed fact sits intact in some chunk.

Common mistakes

  • Judging a parser on easy pages only.
  • Choosing a chunk size from a blog post and never testing it.
  • Dropping headings, dates or units.
  • Appending new versions without removing old ones.
  • Adding permissions after launch.

Checklist

  • Sources have owners, access rules and change detection.
  • Originals are kept with hashes.
  • Parsing is checked on the hardest documents.
  • Chunks follow structure and carry a heading path.
  • Metadata includes version, dates and access.
  • Reruns are idempotent and deletions propagate.
  • Missing permissions mean hidden.
  • A question set measures the effect of every pipeline change.

Frequently asked questions

What chunk size should I start with?

Follow the document's own units where possible. Otherwise start with a few hundred tokens and some overlap, then compare two or three settings on real questions.

Can long context windows replace chunking?

For a few short documents you may send them whole. Large or changing collections still need selection for cost, latency, access control and citations.

Should images be converted to text?

Text descriptions make them searchable with ordinary tools. Visual retrieval models can search page images directly. Test which finds your facts more reliably.

How do I handle documents that contradict each other?

Record effective dates and authority, exclude superseded versions and report real conflicts to the document owners.

References and further reading

Next steps