Skip to content
Goal: Proficient✓ Sources verified 2026-11-24ChunkingEmbeddingpgvector

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)
TermMeaning
ChunkA block of text after splitting; the smallest unit of retrieval
EmbeddingMaps text to a vector; semantically similar texts have nearby vectors
top-kThe first k chunks returned by retrieval
ANN indexApproximate 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:
    1. Fixed length + overlap (simple baseline)
    2. Split by structure: headings, clauses, paragraphs (first choice for contracts and policy documents)
    3. Parent-child chunks: small chunks for retrieval; on a hit, return the larger parent chunk to the model
    4. 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 ​

  1. 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.
  2. 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).
  3. Switching embedding models means rebuilding the whole index: the vector spaces are incompatible.
  4. No citations: answers should cite their source chunks so humans can check them; this is also part of "traceability".

Common interview questions ​

  1. Walk through the full RAG pipeline. What can go wrong at each step?
  2. How do you choose chunk size? Which chunking strategies have you tried?
  3. What's the difference between HNSW and IVFFlat?
  4. What is Contextual Retrieval, and what problem does it solve?
  5. When do you not need RAG, and long context alone works better?

How it relates to my projects ​

Sources ​

Vin Amory · AI development × content creation · Technical notes cite official docs in each page’s sources section