Module 3 · 7 lessons
Retrieval and vector search in depth
How documents are cut up, turned into numbers and searched, and why mixing word search with meaning search works best.
Before you start
From this track: Modules 0 to 2. Each module uses only ideas from the ones before it.
Builds on: Search indexes and autocomplete, Indexes and storage engines
Already know these? Start with the first lesson below.
Later, to go deeper: Message queues and Kafka
1. Cutting documents into chunks
The picture
Cut it up, then search
A long document is cut into short, slightly overlapping chunks, and each chunk gets its own embedding.
Scene 1 of 4 · One long policy
The refund policy has 15,000 words: far too long and too mixed to match one question.
- Refund policy — healthy — 15,000 words
- Chunker — healthy
- Vector index — healthy
- Chunks for this policy
- not shown yet
- One long policy. The refund policy has 15,000 words: far too long and too mixed to match one question.
- Cut into chunks. The chunker cuts it into pieces of 200 new words each: 75 chunks in all.
- Overlap the edges. Each chunk also repeats the last sentence of the one before, so no idea is cut in half.
- One embedding each. Each chunk gets its own embedding, so the index holds 75 of them for this one policy.
- Now you try. Change the chunk size, and see how many chunks the 15,000-word policy becomes. For example: 25 chunks of 600 new words, over this example's 500-word guide. Chunks this big mix several topics, so each embedding is a blur of all of them.
Scene 1 of 4: One long policy. The refund policy has 15,000 words: far too long and too mixed to match one question.
Key points
- A whole document is too long and too mixed to match one question.
- Each chunk holds a few paragraphs about one idea.
- Repeating a sentence across the cut keeps ideas whole.
- Every chunk gets its own embedding in the index.
Before a document can be searched by meaning, it is cut into short pieces called (A short passage cut from a longer document, so it can be turned into an embedding and found on its own.), often a few paragraphs each. Each chunk gets its own (A list of numbers that stands for the meaning of a piece of text. Texts with similar meanings get similar lists.).
A chunk that is too long mixes several topics, so its embedding is vague and matches poorly. A chunk that is too short loses the sentences around it that explain it.
Many systems let neighbouring chunks overlap by a sentence or two. Then an idea split across a boundary still appears whole in one chunk.
In system design: Chunk size and overlap are choices you tune by testing real questions, not fixed rules.
Where it goes wrong
- Cutting at a fixed word count can split a table or a list in half. Cut at headings and paragraphs where you can.
- A chunk can lose what it is about, such as which product a page covers. Adding the page title to each chunk helps.
In an interview
- Say how you chose chunk size and overlap, and how you tested them on real questions.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Engineering guideIntroducing Contextual RetrievalAnthropic engineering blogWhy a chunk cut from its document loses meaning, and a fix measured on real data.
- Research paperRetrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020)Lewis et al., NeurIPSThe original RAG design splits documents into short passages of 100 words each.
2. Finding the nearest chunks fast
The picture
Speed or the true closest
An approximate index checks only likely chunks; checking fewer is faster, but it finds fewer of the true closest ones.
Scene 1 of 4 · Embed the question
The question is turned into an embedding first, by the same model that embedded the chunks.
- Help app — healthy
- Embedding model — healthy
- Vector database — healthy
- Embed the question. The question is turned into an embedding first, by the same model that embedded the chunks.
- Check every chunk. Checking all 10,000,000 chunks finds the true closest 10, but takes about 2 seconds.
- Low effort. Checking only 1,000 likely chunks takes 2 ms, but finds only 7 of the true closest 10.
- A middle setting. Checking 5,000 takes about 10 ms and finds 9 of 10: the usual trade.
- Now you try. Pick an index setting, and see the time against how many of the true closest 10 it finds. For example: 20,000 checks, about 40 ms, finding 10 of the true closest 10. More checks find all 10 here, at a higher cost in time per search.
Scene 1 of 4: Embed the question. The question is turned into an embedding first, by the same model that embedded the chunks.
Key points
- The question becomes an embedding, the same way the chunks did.
- Checking every chunk is exact but takes seconds at this size.
- An index setting decides how many likely chunks to check.
- Recall is the share of the true closest chunks it finds.
At question time, the question is turned into an embedding too. The (A database that stores vectors and finds the ones closest to a given vector, so you can search by meaning.) then finds the chunks whose embeddings are closest to it.
Comparing the question with every chunk is too slow once there are millions. So (A list of numbers. An embedding is a vector.) databases use an (An extra structure, kept sorted or grouped, that lets a database find matching items without reading all of them.) that checks only the likely areas: (Finding the stored vectors closest to a question's vector. The approximate kind checks only part of the data. It is much faster, but now and then it misses a close match.).
Approximate means it can now and then miss a close chunk. In return it answers in milliseconds instead of seconds.
In system design: You trade a little recall, the share of truly closest chunks found, for speed. Settings on the index control that trade.
Where it goes wrong
- Index settings tuned for speed can lower recall with nobody noticing. Measure recall on saved questions after each change.
- An index that keeps growing or changing can get slower or miss more until it is tuned or rebuilt.
In an interview
- Explain the trade between recall and speed, and name the setting that controls it.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperEfficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (2016)Malkov and Yashunin, IEEE TPAMIHow the HNSW graph finds near neighbours quickly, and the settings that trade speed for recall.
- Official docsFaiss wikiMeta AI Research on GitHubIndex types for vector search, from exact to compressed, with their speed and memory costs.
3. Mixing word search and meaning search
The picture
Word search found 0, meaning search 3, and the merged list starts with: I was charged twice for the same order this month.
Word search
No ticket shares a word with this question.
Meaning search
- RefundsI was charged twice for the same order this month.
- RefundsMy package arrived damaged and I need a refund for it.
- RefundsThe item does not match the listing, so I'd like a reimbursement.
Hybrid: both, merged
- RefundsI was charged twice for the same order this month.meaning #1 = 0.016
- RefundsMy package arrived damaged and I need a refund for it.meaning #2 = 0.016
- RefundsThe item does not match the listing, so I'd like a reimbursement.meaning #3 = 0.016
What this simplifies. The tickets and their places on the map are the same as in the meaning map, placed by hand. Real systems use embeddings computed by a model, and a keyword index such as BM25, which also weighs how rare each word is. Each result shows its topic, so you can spot a wrong match, such as a ticket that only shares the word stuck. Each search passes its top 5 to the merge, and the merged score is 1 ÷ (60 + rank) from each list.
Search by meaning finds a refund ticket for the question "money back", even with no word in common. But it can miss exact terms, such as an error code or a product name.
Word search, also called keyword search, is the opposite: it finds exact terms, but misses different words with the same meaning.
(Running a word search and a meaning search together, then merging their results, so a passage found by either can reach the top.) runs both and merges the two ranked lists, so a chunk found by either one can reach the top.
A common way to merge is reciprocal rank fusion: each list gives a chunk 1 ÷ (60 + its rank), and the scores add up. The 60 is a common setting, not a fixed rule.
In system design: Many (The live system that real users reach, as opposed to a test or practice copy.) systems use hybrid search, because people mix exact names with everyday words.
Where it goes wrong
- Word search and meaning search score on different scales, so adding raw scores lets one side win. Merge by rank instead, as rank fusion does.
- Word search can miss a word spelt wrong, so meaning search is still needed beside it.
In an interview
- Give an example query that each kind of search misses, such as an error code or a question in other words.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperReciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (2009)Cormack, Clarke and Büttcher, SIGIRThe short formula most systems use to merge a word-search list and a meaning-search list.
- Engineering guideIntroducing Contextual RetrievalAnthropic engineering blogMeasured gains from adding word search (BM25) to meaning search on the same documents.
4. Reranking the best few
The picture
A careful second look
A reranker reads the question with each top result and rescores them, so the best few reach the prompt.
Scene 1 of 4 · A rough first search
A fast first search returns the top 50 chunks in 15 ms, with a sign-in tip at number 1.
- Help app — healthy
- First search — healthy
- Reranker — healthy
| Chunk | Was | Score | Now |
|---|---|---|---|
| Sign-in tip (highlighted) | #1 | ? | – |
| Depot delays | #2 | ? | – |
| Tracking updates | #3 | ? | – |
| Return labels | #4 | ? | – |
| Lost-parcel rule | #9 | ? | – |
- A rough first search. A fast first search returns the top 50 chunks in 15 ms, with a sign-in tip at number 1.
- Why it ranked first. It shares "stuck" and "for a week" with the question, but it is about the app, not parcels.
- Read each pair. The reranker reads the question with each chunk; all 50 take about 100 ms more.
- The best few. The lost-parcel rule climbs from number 9 to number 1; only the best 2 are sent on to the model.
- Now you try. Choose how many first-search results the reranker rescores. For example: Search and rerank take 25 ms, and the reranker never sees the lost-parcel rule. The first search put it at number 9, below the cut, so no amount of care can find it.
Scene 1 of 4: A rough first search. A fast first search returns the top 50 chunks in 15 ms, with a sign-in tip at number 1.
Key points
- The first search scores the question and each chunk apart, so it is rough.
- A reranker reads the question and a chunk together.
- It is slower, so it only rescores the top few dozen.
- A chunk the first search ranked too low to rescore is never seen.
The first search is fast but rough. A (A slower, more careful model that rescores the top results of a first search, so the best few go into the prompt.) is a second, slower model that reads the question and each top chunk together, and scores how well they match.
Because it is slow, it only rescores the top 20 to 100 chunks from the first search. Then the best few go into the (Everything sent to a language model in one request: instructions, context and the question.).
This two-step shape appears in most search systems: fast and rough over everything first, then slow and careful over a few.
Try the stuck parcel question above: word search pulls in a sign-in ticket. A reranker that reads the whole text would push it down.
In system design: Reranking raises answer quality but adds delay, so count it in your (How long a user waits from sending a request until the first piece of the answer appears.).
Where it goes wrong
- A reranker only sees what the first search found. If the right chunk is not in that first list, reranking cannot bring it back.
- Reranking adds delay to every question. Weigh it against the gain in answer quality.
In an interview
- Describe the two steps: a fast, rough search over everything, then a slower, careful model over the top few.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperPassage Re-ranking with BERT (2019)Nogueira and ChoA model that reads the question and a passage together to rescore the first search’s top results.
- Official docsCross-EncodersSentence Transformers documentationWhy a reranker is more accurate but too slow to run on every document.
5. Measuring search quality
The picture
Did search find the right chunk?
Mark the chunk that answers each saved question, then count how often search puts it in the top k.
Scene 1 of 5 · Mark the right chunk
Each of 8 saved questions is marked with the one chunk that holds its answer.
- Saved questions — healthy — 8 marked questions
- Search — healthy
- Right chunk in top k? — healthy
| Saved question | Right chunk ranked | In top k |
|---|---|---|
| Refund window for shoes? | 1st | – |
| Store credit after 45 days? | 2nd | – |
| Refunds on sale items? | 1st | – |
| Return with no receipt? | 4th | – |
| Swap for another size? | 1st | – |
| Send returns from Canada? | Not in top 10 | – |
| Who pays return postage? | 3rd | – |
| Refund to a gift card? | 1st | – |
- Mark the right chunk. Each of 8 saved questions is marked with the one chunk that holds its answer.
- Note each rank. For every question, record where the search placed its marked chunk in the results.
- Recall at 1. Only 4 of 8 questions have their chunk in first place.
- Recall at 4. Taking the top 4 finds 7 of 8, at the price of a longer prompt.
- Never found at all. "Send returns from Canada?" is never found, whatever k is, so the search itself needs fixing.
- Now you try. Set k, the number of chunks kept, and count the questions whose right chunk is among them. For example: Recall at 2: 5 of 8 questions. A bigger k finds more right chunks, but each one adds tokens to every prompt.
Scene 1 of 5: Mark the right chunk. Each of 8 saved questions is marked with the one chunk that holds its answer.
Key points
- Each saved question names the one chunk that holds its answer.
- Recall at k counts how often that chunk lands in the top k.
- A bigger k finds more, but every extra chunk lengthens the prompt.
- A chunk that is never found needs better chunking, not a bigger k.
A wrong answer has two possible causes: the search missed the right text, or the model misused it. Measure the search on its own, so you know which part to fix.
Take saved questions and mark, for each one, the chunk that holds its answer. Run the search, and note where that chunk ranks.
(The share of test questions whose right chunk appears in the top k search results.) is the share of questions whose right chunk lands in the top k results. A higher k finds more, but every extra chunk makes the prompt longer and costlier.
A question whose chunk is never found needs a different fix: better chunking, a missing page, or word search for an exact term.
In system design: Track recall at k beside answer quality, and measure both again whenever chunking, the embedding model or the index settings change.
Where it goes wrong
- Judging search only by the final answers mixes two causes. Measure recall at k on its own as well.
- Marked questions grow stale as documents change. Update the marked chunks when pages move or are rewritten.
In an interview
- Say how you measure search on its own, such as recall at 5 on marked questions.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperBEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models (2021)Thakur et al., NeurIPSHow search quality is measured with marked answers, and how word and meaning search compare.
- Research paperRagas: Automated Evaluation of Retrieval Augmented Generation (2023)Es et al., EACL demoSeparate scores for the search and the answer, so you can tell which part failed.
6. Keeping the index up to date
The picture
When a page changes
An edited page reaches the index as an event: the indexer replaces that page's chunks, so answers follow the change within minutes.
Scene 1 of 5 · The policy changes
At 09:00 someone edits the help page: refunds now close after 14 days, not 30.
- Help pages — healthy — refunds: 14 days
- Change events — healthy
- Indexer — healthy
- Vector index — healthy — still says 30
- The policy changes. At 09:00 someone edits the help page: refunds now close after 14 days, not 30.
- Wait for the night. A rebuild at 02:00 leaves the old 30-day answer live for 17 hours.
- One event per edit. Instead, the edit puts an event on a queue, and the indexer picks up only that page.
- Replace, not add. It deletes the page's old chunks and writes the new ones, about 1 minute after the edit.
- Keep one model. Switching embedding models needs a second index, filled from every page, before searches move to it.
- Now you try. Pick a way to keep the index up to date, and see what a refund question finds at noon. For example: It finds: only the old 30-day chunk. Out of date for 17 hours. The change waits for the 02:00 rebuild, so the old answer stays live for 17 hours.
Scene 1 of 5: The policy changes. At 09:00 someone edits the help page: refunds now close after 14 days, not 30.
Key points
- A nightly rebuild leaves changed facts wrong for most of a day.
- An event per edit lets one worker re-index only that page.
- Replacing a page means deleting its old chunks, not only adding new ones.
- A new embedding model means re-embedding every page before switching.
Documents change: a price goes up, a policy changes, a page is deleted. The index must follow, or search keeps finding the old text and the model answers from it.
Rebuilding the whole index on a timer is simple but slow to catch up. A common design sends an event for each edit through a (A waiting line for work. One part adds messages, and another takes them off and handles them later, at its own pace.), and a worker re-chunks and re-embeds only that page.
An update must replace, not add: delete the page's old chunks, or both versions stay findable. Storing each chunk's page and version makes this easy.
Vectors from two embedding models cannot be compared. Changing the model means re-embedding every page into a new index, then switching searches over.
In system design: Index updates are a data (A fixed chain of automatic steps, where each step hands its result to the next. A CI/CD pipeline builds, tests and releases every code change.): events, a queue, (Safe to repeat. Doing it twice has the same effect as doing it once.) workers and deletes. Measure how far the index lags behind its sources.
Where it goes wrong
- A deleted page stays findable if its chunks are never removed from the index.
- An indexing worker that falls behind serves old answers with no error. Watch the time from an edit to its index update.
In an interview
- Describe the update pipeline: change events, a queue, workers that can safely run twice, and a measure of the lag.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperRetrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (2020)Lewis et al., NeurIPSShows that swapping the document index updates what the model answers, with no retraining.
- Official docsDebezium documentationDebeziumChange data capture: sending every database change as an event, so an index can follow it.
7. Why a RAG answer is wrong
The picture
- Customer — asks a question — healthy
- Support assistant — searches, then asks — healthy — NOW — question in
- Document index — chunks and vectors — healthy
- Model — writes the answer — healthy
- Question or prompt
- Search
- Chunks or answer
Step 1 of 7 · Support assistant
Done: A customer asks about the Team plan
- What happens
- "How much storage does the Team plan include?"
- Why
- The answer is a fact that changes with each price update, so the assistant looks it up in your documents.
- What changes
- The assistant searches the index first.
- Next
- The index finds the 2 closest chunks
Event log
6 more to go. Press a line to go back to that step.
The index, closest chunk first
Not searched yet.
Step 1 of 7: Support assistant. A customer asks about the Team plan. "How much storage does the Team plan include?"
What this simplifies. The four chunks and their scores are stated examples, not real embeddings, and the model's answer is fixed for each case. A real index holds thousands of chunks, and a real check reads every claim in a long answer. The method is the same: look at what the search found before you blame the model.
When a (Looking up relevant documents first and putting them in the prompt, so the model answers from them instead of from memory alone.) answer is wrong, one of two parts failed: the search or the answer. The fixes are different, so find the failing part first. Look at the chunks sent with the prompt. Is the fact the answer needed in one of them?
If it is not, the search failed. The right page may be missing from the index, ranked too low, or beaten by an old copy that was never deleted.
If it is, the answer failed. The model dropped a detail, mixed up two chunks, or added a fact of its own. Asking it to quote its source, and checking each claim against the chunks, catches much of this.
A missing fact also tests the prompt. Tell the model to reply that it does not know when no chunk answers the question. Otherwise it may fill the gap with a number from somewhere else.
In system design: Log the chunk ids sent with every answer, so a bad answer can be traced to the search or the model. Test each part on its own.
Where it goes wrong
- Changing the prompt when the search failed, or the other way round, wastes days. Look at the chunks that were sent first.
- Without the chunk ids logged, a bad answer from last week cannot be traced to its cause.
In an interview
- Walk through one wrong answer: check the chunks sent, then decide whether the search or the answer step failed.
Check yourself
Two harder questions
The first uses the idea on a new case. The second asks you to judge a design.
Apply it
Judge a design
Sources and further reading (2)
First-hand sources to check this lesson against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.
- Research paperRagas: Automated Evaluation of Retrieval Augmented Generation (2023)Es et al., EACL demoScores for whether the chunks were relevant and whether the answer stayed true to them.
- Official docsReduce hallucinationsAnthropic docs (one provider)Asking the model to quote the text it used, which shows whether it misused good chunks.