part I · chapter 5 of 17

Data engineering and retrieval

Connecting a model to private, live knowledge it was never trained on.

why it matters

The heart of most real AI products, and the place where SQL and Postgres skills pay off most.

before this: chapter 4, Prompt engineering and LLM APIs

in this chapter · 13 sections
  1. 5.1Why retrieval, and not training
  2. 5.2The shape of a retrieval system
  3. 5.3Ingestion: getting clean text out of real documents
  4. 5.4Chunking: deciding what a searchable unit is
  5. 5.5Embeddings: the meaning of a chunk as a vector
  6. 5.6Search: finding the nearest chunks
  7. 5.7Generating an answer with citations
  8. 5.8Private and live data
  9. 5.9Architectures, from simple to elaborate
  10. 5.10Evaluating retrieval
  11. 5.11The maths underneath
  12. 5.12Build it: Project 1, a knowledge assistant
  13. 5.13Where people go wrong

A language model knows what was in its training data, up to the day that data was collected. It knows nothing about your company's documents, your users' records or anything that happened this morning. Most useful AI products need exactly that knowledge, so most useful AI products are built around one pattern: find the relevant information first, then give it to the model along with the question. That pattern is , usually shortened to RAG.

This is the longest chapter in the guide, because it is where most of the real engineering in AI applications happens. It is also where a backend engineer has the biggest head start. Retrieval is data engineering: parsing, cleaning, indexing, querying, permissions and freshness. The model is the last step, not the first.

Why retrieval, and not training

The obvious alternative is to fine-tune a model on your documents so it "knows" them. For facts, that is almost always the wrong tool:

  • Fine-tuning teaches style and format well and facts poorly. The model blends what it learned and still makes things up.
  • Your data changes daily. Retraining for every change is slow and expensive; updating an index takes seconds.
  • A fine-tuned model cannot tell you where an answer came from. Retrieval can cite the exact passage.
  • A fine-tuned model knows everything it was trained on and cannot forget per user. Retrieval can show each user only the documents they are allowed to see.

Fine-tuning has its place, and chapter 11 covers it. Adding knowledge is not it.

The shape of a retrieval system

A RAG system has two halves that run at different times.

Indexing, offline, whenever documents change:

  1. Ingest documents from wherever they live.
  2. Parse them into clean text, keeping their structure and metadata.
  3. Split the text into chunks.
  4. Turn each chunk into an embedding.
  5. Store chunks, embeddings and metadata in an index.

Answering, online, on every question:

  1. Turn the question into a search (an embedding, keywords, or both).
  2. Retrieve candidate chunks the user is allowed to see.
  3. Rerank them and keep the best few.
  4. Put them in the prompt with the question.
  5. Generate an answer that cites its sources, and check the citations.

the shape of a retrieval system

step 1 of 10
indexing, whenever documents changeanswering, on every questiondocumentsparsechunkembedindexquestionembedsearchrerankanswersearch reads the index

indexing · documents

PDFs, web pages, Word files and database rows, wherever your knowledge already lives.

Indexing runs when documents change; answering runs on every question. Most wrong answers start in the top row.

Nearly every failure in a RAG system is a failure in one of those ten steps, and most of them happen before the model is involved. When an answer is wrong, look at what was retrieved before you touch the prompt.

Ingestion: getting clean text out of real documents

Real documents are messy, and the quality of everything downstream is capped by the quality of this step.

PDFs are the hardest common format. A PDF describes where to draw characters on a page, not what the text means: two-column layouts come out interleaved, tables come out as a jumble of numbers, headers and footers repeat on every page. Use a parser that understands layout (Docling and Unstructured are two good open-source options), and look at the output for a sample of your real documents before trusting it.

Scanned documents are images and need OCR to become text. Vision-capable models are increasingly good at this, including tables and handwriting, at a higher cost per page.

HTML needs the navigation, ads and boilerplate stripped. Markdown is the easiest case, and its headings are a gift for chunking. Word and Excel files carry structure (headings, tables, sheets) worth keeping rather than flattening.

As you parse, keep the metadata: source, title, section heading, page number, author, date, language, and above all who is allowed to read it. Metadata is what makes citations, filtering, freshness and permissions possible later. Losing it at ingestion cannot be fixed downstream.

Then make the pipeline behave like a proper data pipeline:

  • Normalise and clean: consistent whitespace and encoding, no repeated headers, no empty chunks.
  • Deduplicate: the same policy document often exists in five places. Hash the content and keep one.
  • Ingest incrementally: track a content hash and a last-modified time per document, and reprocess only what changed.
  • Propagate deletions: when a document is deleted or its permissions change at the source, the index must follow. An index that still serves a deleted document is a data leak.

Chunking: deciding what a searchable unit is

You rarely embed whole documents. A single vector for a fifty-page document averages away everything specific in it, and a whole document would not fit the prompt anyway. So documents are split into , and chunks are what get embedded, retrieved and cited.

The common strategies, from simplest to smartest:

  • Fixed-size: every N tokens. Simple, and it cuts sentences and tables in half.
  • Overlapping: fixed-size windows that overlap by ten to twenty percent, so an idea split across a boundary appears whole in at least one chunk.
  • Recursive: split on the largest natural boundary that keeps chunks under the size limit (sections, then paragraphs, then sentences). A sensible default.
  • Structure-aware: follow the document's own structure (headings, list items, table rows), and prefix each chunk with its heading path so it makes sense on its own: "Refund policy > Damaged items > ...".
  • Semantic: split where the meaning changes, detected by comparing embeddings of neighbouring sentences.
  • Parent-child: embed small chunks for precise matching, but return the larger parent section to the model, so it gets enough context to answer.

cutting a document into chunks

Refunds Items damaged in transit can be returned within 30 days. We refund thefull price, including delivery. Refunds reach your card in five working days.
Returns
Packthe item in its original box if you still have it. Print the labelfrom your order page. Drop it at any post office.

4 chunks · 3 cuts in the middle of a sentence

Every 14 words, wherever that falls. Simple, and it cuts sentences in half.

Chunk size is a trade-off. Small chunks match precisely but lose context; large chunks keep context but dilute the embedding and spend the prompt budget. A few hundred tokens with some overlap is a reasonable place to start. Then measure on your own questions (see "Evaluating retrieval" below), because the right size depends on your documents.

Embeddings: the meaning of a chunk as a vector

An embedding model turns a piece of text into a , typically a few hundred to a few thousand numbers, such that texts with similar meaning get vectors that point in similar directions. "How do I get my money back?" and "refund process" end up close together even though they share no words. That is what keyword search cannot do, and it is why embeddings changed search.

meaning as direction

1234567θ = 3°your questiondimension 1dimension 2

similarity to the question

  1. 2How refunds are paid back0.999
  2. 1Refund policy for damaged items0.998
  3. 3Returning a book you bought0.982
  4. 4Delivery times by region0.883
  5. 5Tracking your parcel0.819
  6. 6Resetting your password0.559
  7. 7Changing your email address0.438

Closest: How refunds are paid back, cos 3° = 0.999.

A toy in two dimensions. Real embeddings have hundreds, but closeness works the same way: the smaller the angle between two vectors, the closer their meaning, and the cosine of that angle is the similarity score.

Choosing an embedding model is its own decision, separate from choosing the chat model:

  • Quality on your domain and languages. Public benchmarks are a starting point; your own retrieval tests decide.
  • Dimension. More dimensions can capture more nuance, and cost more storage and slower search.
  • Maximum input length, which caps your chunk size.
  • Hosted or self-run. Hosted APIs (OpenAI, Cohere and others) are easy; open models (the BGE family, Sentence Transformers) run on your own machines.

Dense embeddings are the vectors above. Sparse representations, such as BM25 scores or learned sparse models, have one dimension per vocabulary word and are mostly zeros; they capture exact terms. Many strong systems use both.

One rule is easy to break and painful to fix: the embedding model is part of the index's schema. Vectors from two different models, or two versions of one model, are not comparable. Store the model name and version with every vector. When you change models, re-embed everything into a new index, backfill it while the old one keeps serving, then switch over, exactly like any other data migration.

Search: finding the nearest chunks

Given a query vector, the exact answer is to compare it with every stored vector and keep the closest. For tens of thousands of chunks that is fast enough (it is one matrix multiplication). For millions it is not, so vector databases use approximate nearest neighbour (ANN) indexes that trade a little accuracy for a great deal of speed:

  • HNSW builds a layered graph in which each vector links to its near neighbours; a search hops greedily through the graph towards the query. Fast and accurate, memory-hungry. Its settings trade recall against speed and memory.
  • IVF clusters the vectors and searches only the few clusters nearest the query. Lighter on memory, sensitive to how many clusters you probe.

Postgres is a vector database

If your data already lives in Postgres, the pgvector extension adds a vector column type, distance operators and HNSW and IVF indexes. You keep one database, transactions, joins, backups, and the row-level security you already know, which matters a great deal below.

create extension if not exists vector;
 
create table chunks (
  id          bigserial primary key,
  document_id bigint not null references documents (id) on delete cascade,
  tenant_id   uuid   not null,
  heading     text,
  content     text   not null,
  embedding   vector(1024) not null,   -- the dimension of your embedding model
  model       text   not null           -- which model made this vector
);
 
create index on chunks using hnsw (embedding vector_cosine_ops);
 
-- the 20 nearest chunks to a query vector, by cosine distance
select id, content, embedding <=> $1 as distance
from chunks
order by embedding <=> $1
limit 20;

Dedicated vector databases (Qdrant, Pinecone, Weaviate, Milvus) earn their place at very large scale or when you need their particular features. Start with pgvector unless you have a measured reason not to.

Keyword search still matters

Embeddings are poor at exact terms: product codes, error messages, names, order numbers, rare jargon. A user searching for "E-4021" wants the document that contains "E-4021", not documents about errors in general. Keyword search handles that. The standard scoring function is , used by Elasticsearch and OpenSearch; Postgres has full-text search built in with tsvector, and extensions add true BM25 ranking.

Hybrid search runs keyword and vector search side by side and merges the results. The usual merging method is reciprocal rank fusion (RRF), which combines ranks rather than raw scores, so you never have to compare a BM25 score with a cosine distance (they are on unrelated scales). The formula is in the maths section below. Hybrid search is one of the most reliable improvements you can make to a RAG system.

hybrid search: two rankings, one list

by meaning (vectors)fused (RRF)by keyword (BM25)1. A Refund policy2. B Damaged parcels3. E Returns by post4. C Error E-40211. C Error E-40212. G E-4021 ticket3. A Refund policy4. D Card errors1. A Refund polic0.03232. C Error E-40210.03203. B Damaged parc0.01614. G E-4021 ticke0.01615. E Returns by p0.01596. D Card errors0.0156

A, Refund policy: 1/(60+1) by meaning + 1/(60+3) by keyword = 0.0323

Search for 'refund failed with E-4021'. Meaning finds the refund documents, keywords find the exact error code, and fusing their ranks puts what both agree on first. No raw scores are compared, only positions.

Filtering

Most real queries come with conditions: this tenant, these document types, newer than last year, documents this user may read. Apply filters inside the search, not after it. If you take the top 20 by similarity and then filter out 18 the user cannot see, you hand the model two chunks and a poor answer. Approximate indexes complicate this, because a filtered search can return fewer results than you asked for; check how your index handles filters, and test with your most selective ones.

Improving the query

Users write short, vague questions. A few techniques improve what gets searched:

  • Query rewriting: ask a fast model to turn the question, plus the conversation so far, into a standalone search query. "What about the second one?" becomes "refund policy for damaged items".
  • Multi-query: generate several phrasings, search with each, merge the results.
  • Query expansion: add synonyms and related terms.

Reranking

The first retrieval is tuned for speed and recall: get the right chunk somewhere in the top 50. A then puts the best ones first. A cross-encoder reranker reads the question and each candidate together and scores how well the candidate answers it, which is far more accurate than comparing two separately computed vectors and far too slow to run on the whole index. So: retrieve 50 cheaply, rerank to the best 5, send those. Hosted rerankers (Cohere and others) and open cross-encoder models both work well.

Context compression goes one step further and trims each retrieved chunk to the sentences that matter, so more evidence fits in the budget.

Generating an answer with citations

The prompt for a RAG answer has a clear structure: instructions, the retrieved passages, each numbered and labelled with its source, then the question.

Answer the question using only the passages below. After each claim,
cite the passage it came from as [1], [2] and so on. If the passages do
not contain the answer, say you could not find it. Do not use any other
knowledge.
 
<passages>
[1] (Refund policy, section 3) Items damaged in transit can be returned
within 30 days for a full refund...
[2] (Shipping FAQ) ...
</passages>
 
Question: <question>Can I get a refund if my book arrived damaged?</question>

Then check the answer in code: every citation number must refer to a passage you actually sent, and an answer with no citations at all should be treated as suspect. Show the citations to the user as links to the source, so they can verify the answer themselves. That one feature does more for trust in an AI product than anything else in this chapter.

Private and live data

Permissions are part of retrieval

The most serious bug a RAG system can have is retrieving a document the user is not allowed to see. Once a passage is in the prompt, no instruction reliably stops the model from repeating it. So permissions are enforced at retrieval, never after generation.

  • Store an owner, a tenant and an access list with every chunk.
  • Filter by them inside every search query.
  • In Postgres, enforce it with , so even a query that forgets the filter cannot return another tenant's rows.
  • Keep permissions in sync with the source system, and treat a permission change like a content change.
  • Test it the way an attacker would: sign in as user A and try to get user B's documents out, directly and through clever questions.
alter table chunks enable row level security;
 
create policy "a tenant reads its own chunks" on chunks
  for select using (tenant_id = current_setting('app.tenant_id')::uuid);

Live data

Not all knowledge belongs in an index. An order's status, an account balance or today's stock level should be fetched live when needed, from your database or an API, and put in the prompt as context. Often the model decides when to fetch, by calling a tool (chapter 7).

Text-to-SQL lets a model write a database query from a question. It is powerful and risky. If you use it, run the generated SQL as a read-only role, against views made for the purpose, with row-level security, a statement timeout and a row limit, and never against a connection that can write.

Architectures, from simple to elaborate

  • Basic RAG: embed the question, retrieve top k, generate. Get this working end to end first.
  • Advanced RAG: add query rewriting, hybrid search, reranking and better chunking. Where most production systems end up.
  • Contextual retrieval: before embedding each chunk, prepend a short, model-written description of where it sits in its document, so a chunk that says "it increased by 3%" carries "Q2 revenue for the India region" with it.
  • Agentic RAG: the model decides whether to search, what to search for, and whether the results are good enough or it should search again. Chapter 7.
  • Multi-hop RAG: questions that need several retrievals in sequence ("Which of our suppliers in Pune had late deliveries, and what does their contract say about penalties?").
  • Corrective and self-checking RAG: the system grades its own retrieved passages or answer and retries when they fall short.
  • Graph RAG: extract entities and relationships into a knowledge graph, and retrieve along the relationships. Useful when questions are about connections across many documents.
  • Multimodal RAG: retrieve images, diagrams and tables as well as text (chapter 10).

Move down this list only when evaluation shows the simpler version failing in a way the next step fixes.

Evaluating retrieval

Measure the two halves separately, because they fail separately.

Retrieval quality: for a set of real questions, record which chunks should have been retrieved, and measure whether they were. The standard measures are recall@k (did the right chunk make the top k?), MRR (how high was the first right chunk?) and NDCG (how good is the whole ranking?).

Answer quality: given the retrieved chunks, is the answer correct, is every claim supported by a cited passage (faithfulness), and are the citations accurate?

If retrieval recall is low, no prompt will save the answer. Fix chunking, search and reranking first. Chapter 12 turns this into a full evaluation pipeline.

The maths underneath

Maths notes 2, 3 and 4 are the mathematics of this chapter.

Similarity. For embedding vectors a\mathbf{a} and b\mathbf{b}, cosine similarity measures the angle between them:

cos⁡θ=a⋅b∥a∥ ∥b∥\cos\theta = \frac{\mathbf{a} \cdot \mathbf{b}}{\lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert}

When vectors are normalised to length one (most embedding models do this, or you should), the denominator is 1, and the squared Euclidean distance is a simple function of the cosine:

∥a−b∥2=2−2cos⁡θ\lVert \mathbf{a} - \mathbf{b} \rVert^2 = 2 - 2\cos\theta

So on normalised embeddings, cosine similarity, dot product and Euclidean distance produce the same ranking. The distance setting in your vector database matters much less than people argue about, as long as it matches how the vectors were normalised.

Brute-force search is one matrix product. Stack the document embeddings as the rows of a matrix EE; then the scores of every document against a query q\mathbf{q} are s=Eq\mathbf{s} = E\mathbf{q}, and the top k are the k largest entries of s\mathbf{s}.

BM25 scores a document DD for a query QQ by adding up, for each query term, how rare the term is and how often it appears in the document, with diminishing returns for repetition and a correction for long documents:

score(D,Q)=∑qi∈QIDF(qi)⋅f(qi,D) (k1+1)f(qi,D)+k1(1−b+b∣D∣avgdl)\text{score}(D, Q) = \sum_{q_i \in Q} \text{IDF}(q_i) \cdot \frac{f(q_i, D)\,(k_1 + 1)}{f(q_i, D) + k_1 \left(1 - b + b \frac{|D|}{\text{avgdl}}\right)}

Here f(qi,D)f(q_i, D) is how often the term appears in the document, ∣D∣|D| is the document's length and avgdl the average length. k1k_1 (typically 1.2 to 2) controls how quickly extra repetitions stop helping, and bb (typically 0.75) how strongly long documents are penalised.

Reciprocal rank fusion merges ranked lists:

RRF(d)=∑r1k+rankr(d),k=60\text{RRF}(d) = \sum_r \frac{1}{k + \text{rank}_r(d)}, \quad k = 60

Say document A is first in the vector results and third in the keyword results, B is second in vector results and missing from keyword results, and C is fifth in vector results and first in keyword results:

DocumentVector rankKeyword rankRRF score
A13161+163≈0.0323\frac{1}{61} + \frac{1}{63} \approx 0.0323
C51165+161≈0.0318\frac{1}{65} + \frac{1}{61} \approx 0.0318
B2none162≈0.0161\frac{1}{62} \approx 0.0161

Documents that both methods like rise to the top, and no score scales had to be compared.

Ranking metrics. Mean reciprocal rank averages one over the position of the first relevant result:

MRR=1∣Q∣∑i=1∣Q∣1ranki\text{MRR} = \frac{1}{|Q|} \sum_{i=1}^{|Q|} \frac{1}{\text{rank}_i}

For three test questions whose first relevant chunk came back at positions 1 and 3, and not at all for the third, MRR is 13(1+13+0)≈0.44\frac{1}{3}\left(1 + \frac{1}{3} + 0\right) \approx 0.44. NDCG rewards putting the most relevant results highest, discounting each position logarithmically:

DCG@k=∑i=1krelilog⁡2(i+1),NDCG@k=DCG@kIDCG@k\text{DCG@}k = \sum_{i=1}^{k} \frac{rel_i}{\log_2(i + 1)}, \qquad \text{NDCG@}k = \frac{\text{DCG@}k}{\text{IDCG@}k}

where IDCG is the DCG of the ideal ordering, so a perfect ranking scores 1.

Build it: Project 1, a knowledge assistant

This is the first of the guide's three projects, and the next two grow out of it.

  1. Upload. An endpoint that accepts PDF and DOCX files and records who uploaded them and who may read them.
  2. Parse and clean. Extract text with structure and metadata; look at the output for your real files.
  3. Chunk. Start with structure-aware recursive chunking with overlap, and prefix each chunk with its heading path.
  4. Embed. Embed every chunk, storing the model name with the vector.
  5. Store. Postgres with pgvector, plus a full-text column for keyword search, with row-level security by tenant and document.
  6. Retrieve. Hybrid search with RRF, filtered by permissions inside the query, then rerank to the top five.
  7. Generate. Send the passages with numbered sources and ask for cited answers, streamed to the user.
  8. Cite. Check the citations in code and show them as links to the source document and page.
  9. Prove the permissions. Two test users, two sets of documents, and a test that tries to get one user's content into the other's answers.

Then write thirty real questions with the chunks that should answer them, and measure recall@5 and MRR. Change one thing at a time (chunk size, hybrid on or off, reranking on or off) and watch the numbers. That habit, more than any single technique, is what makes a retrieval system good.

Where people go wrong

  • Blaming the model for retrieval failures. Look at what was retrieved before changing the prompt.
  • Never looking at the parsed text. Garbage in, confident garbage out.
  • Filtering permissions after retrieval, or in the prompt. Filter in the query, and back it with row-level security.
  • Mixing embedding models in one index. Version your vectors.
  • Vector search alone. Add keyword search; exact terms matter.
  • Tuning without measuring. Thirty labelled questions are enough to start, and far better than none.

you reached the end of the chapter

build this

Project 1: upload documents, chunk, embed into pgvector, answer with citations and per-document permissions.

the maths underneath

  • maths note 2

    Vectors, norms, dot product, similarity

    cos⁡θ=a⋅b∥a∥ ∥b∥\cos\theta = \frac{\mathbf{a} \cdot \mathbf{b}}{\lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert}

    Embeddings are vectors, and semantic search is ranking them by this number.

  • maths note 3

    Matrices and linear layers

    y=Wx+b\mathbf{y} = W\mathbf{x} + \mathbf{b}

    A transformer is mostly matrix multiplication, and brute-force vector search is one matrix times one vector.

  • maths note 4

    Retrieval maths: TF-IDF, BM25, ranking metrics

    RRF(d)=∑r1k+rankr(d)\text{RRF}(d) = \sum_r \frac{1}{k + \text{rank}_r(d)}

    Hybrid search, reranking and retrieval evaluation are these formulas and nothing more.

check yourself

Tick what you could explain to someone else, out loud, without notes.