Skip to main content

Ingestion & Indexing

Customer framing: A customer hands you 40 GB of PDFs, exported HTML, and a ticket database, and asks how long until the assistant works. The answer depends almost entirely on what happens before a single embedding is computed.

Official docs:


The ingestion pipeline​

Everything here runs offline, once per document. Retrieval can only ever be as good as what this leaves behind.

🟧 amber stages are one-way doors β€” changing either forces a full rebuild of the corpus

StageDecidesCost of getting it wrong
ParseWhether the text is even correctUnrecoverable. A bad parse produces a confident wrong embedding.
ChunkThe unit of retrieval and the unit of contextFull re-chunk and re-embed
ContextualiseWhether a chunk means anything on its ownCheap to add later, largest single recall win
EmbedThe semantic half of hybrid searchFull re-embed of every chunk
IndexRecall vs latency, and what you can filter onRebuild only. The knobs are tunable in place.

The one thing worth internalising: cost rises left to right, and so does the damage. A parsing bug is invisible at every later stage and survives every amount of retrieval tuning. Spend your time at the left.

β†’ The query-time counterpart is the retrieval pipeline.


Parsing comes first​

No retrieval tuning recovers from a bad parse. A mis-parsed table does not produce an empty embedding, it produces a confident wrong one. Budget more time here than on chunking.

SourceWhat breaksWhat to do
Native PDFReading order in two-column layouts, repeated headers and footersLayout-aware parser, strip repeating lines per page
Scanned PDFOCR errors baked into the text silentlyOCR with per-character confidence, quarantine low-confidence pages
HTMLNav bars, cookie banners, and footers embedded into every chunkExtract the main content node, drop boilerplate before chunking
DOCX, PPTXNothing much. Structure is in the file already.Use headings and slide titles as chunk metadata
Tickets, DB rowsNothing. It is already structured.Template each row into a short document, keep the ID

Tables are the hard part. Linearising a table to plain text destroys the row-column binding, so "Enterprise plan, 30 day retention" becomes three loose words in a bag. Three options, in order of effort:

  1. Serialise each table to markdown and keep it in one chunk. Cheap, works up to roughly 30 rows.
  2. Emit one chunk per row with the header prepended: Plan: Enterprise | Retention: 30 days | SLA: 4h. Survives chunking, retrieves precisely.
  3. Keep tables in Postgres as real rows and query them alongside the vector search. Correct, and more plumbing.

Whatever parser you use, the two settings that matter are the layout model over raw text extraction, and table structure inference so tables come back as HTML rather than soup. In unstructured those are strategy="hi_res" and infer_table_structure=True.

warning

Read the parsed output of ten random documents with your own eyes before building anything on top of it. This single habit catches more RAG failures than any metric.


Chunking​

A chunk is the unit of retrieval and the unit of context. Those two pull in opposite directions: small chunks retrieve precisely, large chunks answer completely.

StrategyHowUse when
Fixed-sizeN tokens, fixed overlapBaseline. Uniform prose with no structure.
RecursiveSplit on paragraph, then sentence, then token, until under the limitDefault choice for mixed documents
StructuralSplit on markdown headings or HTML sectionsDocs with real headings. Best quality per unit of effort.
SemanticSplit where consecutive sentence embeddings divergeLong unstructured transcripts. Costs an embedding pass.
Document-awarePer row, per slide, per functionTables, code, slide decks
Source## API Keys β€” Keys must be rotated every 90 days. ## Provisioning β€” New tenants get a sandbox first.Fixed-sizecuts mid-sentence Β· headings orphanedRecursivebreaks on paragraphs Β· headings still orphanedStructuralone chunk per section Β· breadcrumb comes free

Start at 500 to 800 tokens with 10 to 15 percent overlap, then move it based on eval scores, not taste.

Always prepend context to the chunk. "It must be rotated every 90 days" is unretrievable and unusable on its own. Prefixed with Meridian Support Assist > Security Policy > API Keys, it is both.

Best practice

Prepend the document title and section breadcrumb to every chunk before embedding. Three lines of code, and usually the largest single recall win available. β†’ An LLM-written version of this is contextual retrieval, which measures even better.


Embeddings​

DecisionRule
Model familyPick a retrieval-tuned model, not a general sentence encoder. Check MTEB retrieval, not the overall average.
Hosted or self-hostedSelf-host if you are airgapped or re-embedding often. Hosted otherwise.
DimensionalityHigher recall, linearly higher memory and index cost
Max inputMust exceed your chunk size plus the breadcrumb, or you silently truncate
Asymmetric prefixesSome models need query: and passage: prefixes. Skipping them quietly costs recall.

Index memory is easy to estimate and easy to forget:

400,000 chunks Γ— 1536 dims Γ— 4 bytes β‰ˆ 2.4 GB of raw vectors, plus 30–50% again for the HNSW graph.

Matryoshka models let you truncate 1536 dimensions to 512 and keep most of the recall. That is a 3x cut in index memory for a few points of recall, and it is usually the right trade at corpus scale.

One-way door

Changing the embedding model means re-embedding the entire corpus and rebuilding every index. Decide it once, deliberately, and write down why.


Metadata and multi-tenant isolation​

Anything you filter on must be a column, not a key inside a JSON blob. Filtering is part of the query plan, and the planner cannot help you if the value is buried.

Minimum useful metadata per chunk: tenant_id, doc_id, source_uri, section_path, updated_at, acl_group.

Isolation modelBlast radius of a bugOps costUse when
Shared table, tenant_id filterEvery tenantLowMany small tenants, and RLS is on
Schema per tenantOne tenantMediumTens of tenants, per-tenant retention rules
Database per tenantOne tenantHighRegulated or airgapped tenants

Meridian runs shared tables for the 117 cloud tenants and separate databases for the three on-prem ones.

Enforce isolation in the database, not the application. Turn on row-level security and write one policy binding tenant_id to the session. One forgotten WHERE tenant_id = ... in one code path is a cross-tenant leak, and there is always one code path.

Pre-filter versus post-filter is not a detail. A tenant holding 1% of the corpus gets far fewer than k results β€” sometimes zero β€” if the ANN index searches globally and the filter is applied afterwards. β†’ Selectivity breaks ANN, not BM25


Choosing the vector store​

OptionFilteringHybrid searchOps burdenPick it when
pgvectorNative SQL, RLSNeeds tsvector plus manual fusionLowest if you already run PostgresThe data already lives in Postgres. Default.
QdrantStrong payload filters, pre-filtered searchBuilt inMedium, self-hostableFilter-heavy workloads, on-prem
WeaviateGoodBuilt in, tunable alphaMediumYou want hybrid without writing fusion
PineconeGood, namespaces per tenantSparse plus denseNone, it is managedYou want zero ops and accept lock-in

Under roughly 10 million vectors, pgvector with HNSW is fast enough and you keep joins, transactions, backups, and RLS. Reach for a dedicated store when you outgrow one node or need pre-filtered search that Postgres cannot plan well.


HNSW vs IVFFlat​

Both are approximate. Recall is a dial you set, not a property you receive.

layer 2few nodes, long hopslayer 1layer 0every vectorentrynearest neighbourgreedy descent β€” coarse hops first, refine at the bottom

HNSW builds that layered graph once and walks it per query. ef_search is how many candidates it keeps in flight during the walk β€” the dial. IVFFlat instead clusters vectors around k-means centroids and scans only the nearest probes lists.

HNSWIVFFlat
StructureNavigable small-world graphInverted lists around k-means centroids
Build timeSlowFast
MemoryHigh, graph lives in RAMLow
Query speed at high recallFasterSlower
Needs data before buildNoYes, it clusters existing rows
Handles heavy insertsYesDegrades, needs rebuilds
Knobsm, ef_construction, ef_searchlists, probes
KnobSet it toWhen
m16Build time. Fine for most corpora.
ef_construction64Build time. Raise only if recall plateaus low.
ef_search40 β†’ 200Runtime dial. Buys recall, costs latency. First thing to tune when retrieval misses.
lists (IVFFlat)rows / 1000, or sqrt(rows) past a millionBuild time
probes (IVFFlat)sqrt(lists)Runtime dial
Best practice

Choose HNSW unless build time or memory forces your hand. Then measure recall against exact search on 200 queries and set ef_search from the curve, not from a blog post.


Keeping the index current​

ChangeCheapest correct move
New documentInsert chunks. HNSW absorbs inserts fine.
Edited documentDelete chunks by doc_id, insert new ones. Never patch in place.
Deleted documentHard delete, then confirm it is gone from retrieval. Tombstones leak.
Changed chunking strategyFull rebuild
Changed embedding modelFull rebuild, blue-green

Blue-green is the only rebuild pattern worth writing down: build the new index into a second table, verify recall on the eval set, swap the two names in a single transaction, keep the old table for a day.

Right-to-be-forgotten requests are a deletion path with a deadline. Make sure it reaches the index, the embedding cache, and the retrieval logs.

β†’ See Production for the ingestion pipeline as a scheduled job.

β†’ Next: Retrieval.