The RAG Pipeline and Document Chunking
In B2B settings, RAG is often used to let the model consult a customer's rule library, past contracts or product manuals.
Core concepts
RAG (Retrieval-Augmented Generation) = retrieve relevant material first, then put it in the context for the model to answer from. There are two pipelines:
Offline indexing: documents → parsing (PDF/OCR) → cleaning → chunking → embedding → write to vector store + full-text index
Online query: question → (rewrite) → retrieve top-k → (rerank) → assemble context → LLM generation (with citations)| Term | Meaning |
|---|---|
| Chunk | A block of text after splitting; the smallest unit of retrieval |
| Embedding | Maps text to a vector; semantically similar texts have nearby vectors |
| top-k | The first k chunks returned by retrieval |
| ANN index | Approximate nearest neighbor index (HNSW, IVFFlat), trading a little recall for speed |
How it works: why chunking strategy affects recall
- Chunks too large: one chunk mixes several topics, its vector gets "averaged out", and similarity to a specific question drops; it also eats context.
- Chunks too small: context is lost, e.g. it becomes unclear what "this clause" refers to.
- Common strategies:
- Fixed length + overlap (simple baseline)
- Split by structure: headings, clauses, paragraphs (first choice for contracts and policy documents)
- Parent-child chunks: small chunks for retrieval; on a hit, return the larger parent chunk to the model
- Contextual Retrieval (Anthropic, 2024): prepend to each chunk an LLM-generated note describing "this chunk's context within the whole document" before embedding and BM25. In the official experiments, the top-20 retrieval failure rate dropped by 49%, and by 67% with reranking added.
Vector indexes (pgvector as the example)
- The default is exact search; adding an HNSW or IVFFlat index makes it approximate search.
- HNSW: a better speed/recall trade-off at query time, but slower to build and uses more memory. IVFFlat: faster to build, less memory.
- Each distance function (L2, inner product, cosine) needs its own index (with the matching operator class).
In practice: a minimal pgvector table
sql
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunk (
id bigserial PRIMARY KEY,
doc_id bigint NOT NULL,
heading text, -- section heading, handy for citations
content text NOT NULL,
embedding vector(1024), -- dimension must match the embedding model used
tsv tsvector GENERATED ALWAYS AS (to_tsvector('simple', content)) STORED
);
CREATE INDEX ON chunk USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON chunk USING gin (tsv);
-- cosine distance top-5
SELECT id, heading, content FROM chunk ORDER BY embedding <=> $1 LIMIT 5;Common pitfalls
- Parsing quality sets the ceiling: if tables, scans, headers and footers aren't handled well, no amount of tuning later will help. Look at the parsed output by hand first.
- Chinese full-text search: PostgreSQL's built-in configurations don't segment Chinese words, and the
'simple'configuration works poorly for Chinese. You need an extension such as zhparser / pg_jieba, or segmentation in the application layer (⚠️ check the extension's maintenance status before choosing one). - Switching embedding models means rebuilding the whole index: the vector spaces are incompatible.
- No citations: answers should cite their source chunks so humans can check them; this is also part of "traceability".
Common interview questions
- Walk through the full RAG pipeline. What can go wrong at each step?
- How do you choose chunk size? Which chunking strategies have you tried?
- What's the difference between HNSW and IVFFlat?
- What is Contextual Retrieval, and what problem does it solve?
- When do you not need RAG, and long context alone works better?
How it relates to my projects
- AI Document Review Pipeline W4: pgvector + hybrid search + rerank, used to retrieve the customer's review rules and past cases.
- Next page: Hybrid Search and Rerank.
Sources
- Anthropic: Introducing Contextual Retrieval (2024-09) — source of the 49% / 67% figures and the experiment setup
- pgvector GitHub README — exact vs approximate search, HNSW vs IVFFlat, indexes and distance functions
- Lewis et al., 2020 · Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (arXiv 2005.11401) — the original RAG paper
- PostgreSQL Docs: Full Text Search
