Lesson 4.2: Similarity search
Learn how to find the closest vectors to a query: exact and approximate search, top-k, filters, hybrid keyword and vector ranking, and how to measure recall.
Once you can turn text into vectors, the next job is to use them: given a question, find the handful of stored pieces whose vectors are closest to the question's vector. That sounds like a simple loop, and for a small collection it is. But a real product may hold millions of vectors, answer many questions a second and need to respect rules such as "only show documents this user may see". At that point, how you search matters as much as how you embed. By the end of this lesson you will be able to explain exact nearest-neighbour search and estimate what it costs, say what top-k means and how to choose k, explain why approximate search exists and measure how much it gives up with a number called recall, combine metadata filters with vector search without losing results, blend keyword search and vector search into one ranking with a simple formula, and judge a retrieval system with a handful of test questions. You should have read Lesson 4.1, on what an embedding is, because we use its ideas of cosine similarity and vector size. You do not need advanced mathematics, and every calculation is shown.
The task: find the nearest vectors
Imagine a help centre with 1,000,000 pieces of text, each stored as a vector of 768 numbers. A customer types "how do I get my money back", and the system turns that into a query vector of the same length. The task is to return the pieces whose vectors are most similar to the query vector, usually the best five or ten. This is called nearest-neighbour search, or similarity search. The answer is a short ranked list, from most similar to least.
The simplest method is to compare the query with every stored vector, one after another, compute the similarity for each and keep the best. This is called brute force or exact search, because it always finds the true best answers. There is no cleverness, no shortcut and no risk of missing something.
How long does it take? For each stored vector, you multiply 768 pairs of numbers and add them up, which is about 768 multiplications and additions. For a million vectors, that is about 768 million of these operations for one query. A modern processor, running well-optimised code, can do something of the order of tens of billions of such operations a second. At 20 billion a second, one query takes about 768,000,000 ÷ 20,000,000,000, which is 0.038 seconds, or about 38 milliseconds. That is quick enough for one user. For 100 users a second, you would need many processors. And at 100 million vectors, one query takes about 3.8 seconds, which is too slow for a search box.
The cost grows in a straight line with the number of vectors. Ten times more data means ten times more work. Try your own figures below.
Top-k: how many results to return
You rarely want the single nearest vector. You want the top k, a short list of the k best matches, where k might be 3, 5 or 10. Choosing k is a balance.
A small k returns only the very best matches. It is quick and keeps the answer focused, but if the right piece is ranked fourth, you will miss it.
A large k is more likely to include the right piece, but it brings in more weak matches, which cost time and, when you pass them to a language model later, take up space in its context window and may distract it.
The right k comes from testing. A common pattern is to retrieve a larger list, say 20, and then use a second step to pick the best five. The next lessons in this track return to that idea, which is called reranking.
Some systems also use a similarity threshold: they return only results above a certain score. This helps with questions that the collection cannot answer. If the best match scores 0.31, you probably have nothing relevant, and it is better to say so than to return the least bad piece. But as Lesson 4.1 warned, a good threshold depends on your model and your data. Measure it on your own examples.
Predict first: a search returns the top 5 for a question, and the correct piece is at position 7. What happens, and what could you change? Think before you read on.
The correct piece is not in the list, so the system cannot use it, even though the embedding put it quite close. You could raise k to 10, which would include it, at the cost of more noise. Or you could keep a large k for retrieval and add a reranking step. The point is that search quality is partly a question of which list you hand on.
Making search fast: normalising vectors
A simple trick speeds up every comparison. If you scale each vector to a length of exactly 1 when you store it, then the cosine similarity between two vectors equals their dot product. The dot product needs no division and no square roots, which makes it cheaper and easier to speed up. Many embedding models return vectors that are already scaled to length 1, and many search systems normalise vectors on the way in. Check what yours does. If you mix normalised and un-normalised vectors, rankings can be wrong, because length will affect the dot product.
When brute force is too slow: approximate search
At some size, comparing against everything is too slow or too expensive. The answer is approximate nearest-neighbour search, often shortened to ANN. The idea is to build a helper structure, called an index, in advance, so that a query examines only a small part of the collection and still finds nearly all of the true nearest neighbours. The next lesson explains how the main kinds of index work. Here we need only the trade-off.
Approximate search gives up a little accuracy for a lot of speed. It may return nine of the true ten best matches and miss one, or swap a true match for a slightly worse one. The measure of this is recall.
Recall at k is the share of the true top k results, as found by exact search, that the approximate search also returns. If exact search says the ten nearest vectors are A to J, and the approximate search returns A, B, C, D, E, F, G, H, I and K, then it found 9 of the true 10. The recall at 10 is 9 ÷ 10 = 0.9, or 90 per cent.
Higher recall costs more time. A good index lets you choose the balance with a setting, and the right choice depends on the application. For a help-centre search that feeds a language model, 95 per cent recall at k may be plenty, because the true list contains near-duplicates and the answer rarely depends on the tenth-best vector. For a task where missing one record matters, such as finding every document that mentions a legal term, you want exact search or very high recall.
Note what recall does not measure. It compares the approximate search with exact search, not with what the user wanted. If the embedding model ranks the wrong things highest, perfect recall will faithfully return the wrong things. So there are two separate questions: does the index find what exact search would find (recall), and does exact search find what people need (retrieval quality, covered below)?
Filters: searching only some of the vectors
Real products rarely search everything. A user should see only documents from their own organisation. A support search might be limited to one product, one language or documents updated this year. These conditions are metadata filters, because they use facts about the text, such as its owner, language and date, that are stored beside the vector.
There are two ways to combine a filter with vector search, and the difference matters.
Post-filtering: search first, then discard results that fail the filter. Simple, but dangerous. Suppose you ask for the top 10, and only 2 of those pass the filter. You return 2 results, even though many more matching documents exist further down the ranking. If the filter is strict, you may return nothing.
Pre-filtering: apply the filter first, and search only among the vectors that pass. This returns the best k from the allowed set, as you would expect. It needs support from the index, because the index has to search within a subset, which is harder to do fast.
A numerical example shows the risk of post-filtering. A collection has 1,000,000 vectors, and a user is allowed to see 1 per cent of them. You retrieve the top 10 and then filter. Roughly speaking, each of the top 10 has a 1 in 100 chance of being allowed, so the expected number you keep is 10 × 0.01 = 0.1. Most of the time, you return nothing. To get 10 allowed results by post-filtering, you would need to retrieve about 1,000 and then filter. The cost of poor filtering is not a speed problem but a missing-results problem.
Real filters interact with results in more complicated ways: allowed documents may be more or less similar to the query than the average, so the simple calculation is a guide and not a promise. But the lesson is sound: for strict filters, use an index that filters during search. Also, think of access control as a filter that must never fail. A search that shows one customer's documents to another is a security failure, not a ranking problem. Lesson 8.3 returns to privacy.
Keyword search is not dead: hybrid search
Embeddings are good at meaning and poor at exact strings. A search for the error code "E-4012", a product code or a person's name may do better with a plain keyword match. Conversely, keyword search misses "money back" when the article says "refund". The two methods have opposite strengths, and many production systems run both and combine the results. This is called hybrid search.
Keyword search uses a different kind of index, built on the words themselves, and a scoring formula that rewards documents that contain the query's rarer words many times. A widely used family of such formulas is known as BM25. You do not need its details here. What matters is that it gives a ranked list that is independent of the vector list.
How do you merge two ranked lists? Their scores are not comparable: a vector similarity of 0.8 and a keyword score of 14.2 are on different scales. A simple and popular method ignores scores and uses only the ranks. It is called reciprocal rank fusion, or RRF. For each document, add up 1 divided by (a constant plus its rank) from each list in which it appears. A common constant is 60, which softens the effect of small rank differences. Documents that rank well in both lists rise to the top.
A worked example. Three documents appear in the two lists.
Document · Rank in vector list · Rank in keyword list · RRF score with constant 60A · 1 · 5 · 1/61 + 1/65 = 0.0164 + 0.0154 = 0.0318
B · 2 · 1 · 1/62 + 1/61 = 0.0161 + 0.0164 = 0.0325
C · 3 · 12 · 1/63 + 1/72 = 0.0159 + 0.0139 = 0.0298
Document A is the vector search's favourite, but B is high in both lists, so B comes first overall, with A second and C third. This is the kind of result you want: documents that both methods like are more likely to be right.
Hybrid search is not always necessary. If your queries are natural questions and your documents are prose, vector search alone may do well. But if users search by codes, names or exact phrases, adding keyword search is usually the biggest single improvement.
Judging a retrieval system
You cannot improve search without measuring it. The method is simple.
1. Collect test questions. Write 30 to 100 realistic questions, ideally from real users.
2. For each, mark the pieces that answer it. One or two correct pieces per question is typical.
3. Run the search and see where the correct piece appears.
4. Score it. Two measures are common.
Hit rate at k is the share of questions for which at least one correct piece appears in the top k. Mean reciprocal rank, or MRR, takes the rank of the first correct piece for each question, turns it into 1 divided by the rank (so rank 1 gives 1, rank 2 gives 0.5, rank 3 gives 0.33, and no hit in the list gives 0), and averages over the questions.
A small example, with five questions.
Question · Rank of the first correct piece · Reciprocal rank · In the top 3?Q1 · 1 · 1.00 · Yes
Q2 · 3 · 0.33 · Yes
Q3 · 2 · 0.50 · Yes
Q4 · Not in the top 10 · 0.00 · No
Q5 · 1 · 1.00 · Yes
The hit rate at 3 is 4 out of 5, or 80 per cent. The MRR is (1.00 + 0.33 + 0.50 + 0 + 1.00) ÷ 5 = 2.83 ÷ 5 = 0.57. Neither number is "good" or "bad" on its own. They are tools for comparing choices: a different embedding model, a different k, hybrid or plain. If switching to hybrid search raises the hit rate at 3 from 80 to 92 per cent on the same questions, that is a real improvement. The evaluation lessons in Module 6 go deeper into building and using such test sets.
A second worked example: choosing between exact and approximate search
A company has 2,000,000 vectors of 768 dimensions and expects 200 queries a second at peak. Exact search needs 2,000,000 × 768 = 1.536 billion operations per query. At 20 billion operations per second per core, one query takes about 77 milliseconds on one core, and 200 queries a second need about 15 cores for the comparisons alone. That is feasible, but costly. An approximate index that examines about 2 per cent of the vectors would cut the work by about fifty times, to roughly one or two cores, at a recall of perhaps 95 per cent. Whether to accept the 5 per cent loss depends on the product: if retrieval feeds a language model that sees ten pieces, losing one of the ten nearest, usually a near-duplicate of another, is rarely visible. The decision is made by testing recall on your own data, and not by rule.
A third worked example: access control
A software company stores support documents for 500 customers in one collection of 5,000,000 vectors. Each customer should see only their own, about 10,000 vectors, or 0.2 per cent. Post-filtering the top 10 would leave 10 × 0.002 = 0.02 results on average, so nearly every query would return nothing. Instead, the company uses pre-filtering by customer, so that each search runs over only that customer's 10,000 vectors. It is also faster, because 10,000 vectors is a small search. The design choice, filter inside the search and not after it, made the product work.
Common mistakes
Treating brute force as a failure. For collections of up to a few hundred thousand vectors, exact search is simple, correct and often fast enough. Do not add an index you do not need.
Choosing k by habit. Test a few values on your own questions.
Post-filtering strict filters, which can return empty results.
Mixing normalised and un-normalised vectors, which makes dot products misleading.
Using only vector search for codes and names. Add keyword search for exact strings.
Setting a similarity threshold by copying a number, instead of measuring on your own data.
Never measuring. Without test questions, you cannot tell whether a change helped.
Forgetting that recall is relative to exact search, and not to what the user wanted.
Key takeaways
Similarity search returns the k stored vectors closest to a query vector. Exact search compares with every vector, always finds the true best, and costs time in proportion to the collection size.
Choose k by testing. A larger k includes more correct answers and more noise, and reranking can sort out the difference.
Approximate search trades a little accuracy for a lot of speed. Recall at k says what share of the true top k it finds.
Apply strict metadata filters during the search, not after, or you may return too few results. Treat access control as a filter that must never fail.
Hybrid search combines vector and keyword rankings. Reciprocal rank fusion merges two lists using only their ranks.
Measure with a set of real questions: hit rate at k and mean reciprocal rank let you compare choices.
Check yourself
1. A collection has 5,000,000 vectors of 1,000 dimensions. Roughly how many multiply-and-add operations does one exact search need?
5,000,000 × 1,000 = 5 billion operations.
2. Exact search finds the true top 20. An approximate search returns 18 of them. What is the recall at 20?
18 ÷ 20 = 0.9, or 90 per cent.
3. Why can post-filtering return no results when pre-filtering would not?
Post-filtering discards results from a short list, and if few of those pass the filter, little remains. Pre-filtering searches only the allowed vectors, so it returns the best k among them.
4. Document X is ranked 2 in the vector list and 4 in the keyword list. With a constant of 60, what is its reciprocal rank fusion score?
1/62 + 1/64 = 0.0161 + 0.0156 = 0.0318.
5. Why might a search for the error code "E-4012" work better with keyword search than with embeddings alone?
Embeddings capture meaning, not exact strings, so a specific code may not stand out, while a keyword match finds the exact text.
6. Four of five test questions have a correct piece in the top 3. What is the hit rate at 3?
4 ÷ 5 = 80 per cent.
Try this
Set aside 30 to 45 minutes. You need a spreadsheet; the last step is optional and needs a search tool you are allowed to use.
1. Choose a collection you could search, such as help articles, meeting notes or product descriptions. Write down roughly how many pieces it has and the vector size you would use. Use the first simulator to estimate the time for one exact search at 20 billion operations a second, and the cores you would need at a query rate you pick.
2. Decide whether exact search is enough. Write one sentence of reasoning that uses your numbers.
3. Write ten realistic questions a user might ask. For each, write the title of the piece that should answer it.
4. Invent plausible rankings for five of the questions, from a vector search and a keyword search, as lists of the top five titles. Compute the reciprocal rank fusion score for every title that appears, with a constant of 60, and write the fused top three for each question.
5. For your five questions, record the rank of the correct piece in the vector list alone and in the fused list. Compute the hit rate at 3 and the mean reciprocal rank for each. Note whether fusion helped.
6. Name one filter your product would need, such as language or customer. Use the post-filter simulator to find how many results you would need to retrieve before filtering, and decide whether pre-filtering is needed.
7. Optional: if you can run a real search, compare your invented ranking with the real one on three questions.
A good result is a short page with your size and speed estimate, a decision on exact against approximate search with a reason, a small table of hit rate and mean reciprocal rank for vector alone and fused rankings, and a note on how you would apply a filter.
Tags: AI Engineering Similarity search Vector search Hybrid search Retrieval