Sub topic 5
Approximate nearest neighbor search and recall
This chapter assumes you can write the brute-force search from the previous chapters. You should also know that a dot product on normalized vectors gives cosine similarity, and that exact search scores every stored vector for each query.
Why approximate search exists
Exact search costs O(N·d) per query, where N is the number of vectors and d is their dimension. At millions of vectors this is too slow and too memory-hungry for interactive use. Approximate nearest neighbor (ANN) search gives up a guarantee of exactness. It examines only a small part of the data and returns neighbors that are probably the true ones.
An ANN index is a data structure built ahead of time. It lets a query skip most vectors. Different index families skip them in different ways: HNSW follows graph edges, and IVF visits only a few clusters. Later chapters cover both.
Recall
Recall measures how much of the true answer the index finds. For one query:
recall@k = |approximate top-k ∩ exact top-k| / k
If the exact top 10 and the index's top 10 share 9 ids, recall@10 is 0.9. Average this over many queries to get a figure for the index.
Recall is measured against the exact result, so you need an exact baseline. Latency, memory and recall pull against each other, and every ANN parameter moves you along that trade-off.
Measuring recall in practice
The code below builds an exact FAISS index and an HNSW index on the same data. It then compares their results.
import numpy as np
import faiss
d = 64
xb = np.random.default_rng(0).normal(size=(10000, d)).astype("float32")
xq = xb[:100]
k = 10
flat = faiss.IndexFlatL2(d)
flat.add(xb)
_, true_ids = flat.search(xq, k)
hnsw = faiss.IndexHNSWFlat(d, 32)
hnsw.hnsw.efConstruction = 200
hnsw.add(xb)
hnsw.hnsw.efSearch = 64
_, ann_ids = hnsw.search(xq, k)
recall = np.mean([len(set(a) & set(t)) / k for a, t in zip(ann_ids, true_ids)])
print(f"recall@{k}: {recall:.3f}")IndexFlatL2 is the exact baseline. efSearch is the number of candidates HNSW keeps while searching. Raising it increases recall and latency. Lowering it does the opposite.
Common errors
- Evaluating on queries copied from the data. The example above uses the first 100 stored vectors as queries, so each query's nearest neighbor is itself. This is fine for a demonstration. For real tuning, use held-out queries that resemble production traffic.
- Reporting recall without latency. A recall of 0.99 is not useful if queries are as slow as brute force. Always report both numbers, ideally as a curve across several parameter settings.
- Using a metric that does not match the baseline. The index and the exact search must use the same distance. If your embeddings are meant for cosine similarity, normalize them for both.
- Judging recall on random data. Random Gaussian vectors have little structure, so the results can differ from real embeddings. Test on your own data.
- Mixing up recall and relevance. Recall only says the index matches exact search. If the embedding model returns poor results, a perfect-recall index returns the same poor results faster.
Choosing a target
A target of 0.95 to 0.99 recall@10 is common. Many applications, such as retrieval for a language model, tolerate a few misses because the exact top 10 are often near-duplicates in quality. Set the target from the application's tolerance, then tune the cheapest parameters that reach it.
Exercise
An HNSW index returns these ids for one query: [4, 9, 12, 7, 31]. The exact top 5 are [4, 9, 7, 15, 31]. What is recall@5 for this query, and what would you change first if the average across queries is too low?
Show answer
The overlap is {4, 9, 7, 31}, which is 4 ids, so recall@5 is 4/5 = 0.8. The first thing to change is the search-time parameter, efSearch, because raising it increases recall without rebuilding the index. It costs higher latency, so check latency after the change.
Exercise
Why must recall be measured against exact search results rather than against labels of which documents are relevant?
Show answer
Recall evaluates the index, which is meant to reproduce exact nearest neighbor search. Relevance labels evaluate the embedding model and the whole retrieval pipeline. Mixing them makes it unclear whether a miss comes from the index or from the embeddings.