Sub topic 5
Approximate nearest neighbor search and recall
This chapter assumes you can write basic Python, know what an embedding is, and have seen exact nearest neighbor search (a brute-force scan of every vector). You should also know that a database index trades extra work at write time for faster reads. Here you will learn what approximate search gives up, how that loss is measured as recall, and which mistakes make the measurement misleading.
Why accept approximate answers
Exact search compares the query with every stored vector. The cost grows linearly with the number of vectors and with the dimension. For a million 768-dimensional vectors, one query needs about 768 million multiply-adds. At hundreds of queries per second, a single machine cannot keep up.
Approximate nearest neighbor (ANN) search avoids the full scan. An ANN index is a data structure that steers the search toward a small set of promising candidates, then scores only those. It may skip a true neighbor, so the result can differ from the exact one. In return, it can be 10 to 1000 times faster.
This trade is usually acceptable because embeddings are already approximate. The ranking among the 8th, 9th and 10th closest items is often noise from the embedding model. Missing one of them rarely changes what a user sees. Missing the single best match can matter, and that is why you measure the loss instead of assuming it is small.
The shape of an ANN query
Most ANN indexes work in two phases. They differ in how they produce candidates.
The lower branch of the diagram is only for evaluation. In production you run just the upper path. The exact search exists to tell you how much the upper path lost.
Recall
Recall@k is the fraction of the true top k neighbors that the approximate search also returned. For one query:
recall@k = |approximate top k ∩ exact top k| / kIf the exact top 10 and the approximate top 10 share 9 ids, recall@10 is 0.9. You average this over many queries to get the recall of an index configuration.
Some details are easy to miss:
- Recall counts membership, not order. Two lists with the same ids in different order have recall 1.0. If order matters, also check ranking quality separately.
- Recall depends on k. An index can have recall@1 of 0.85 and recall@100 of 0.97, so state k whenever you quote a number.
- Ties and near-ties blur the definition. If the 10th and 11th neighbors are almost equidistant, swapping them costs you recall but not result quality. Some teams count a result as correct if its distance is within a small tolerance of the true k-th distance.
Measuring it in code
The script below builds an exact index as ground truth and an HNSW index (covered in a later chapter) over the same data. It then sweeps efSearch, the HNSW parameter that sets how many candidates the search keeps in play. The queries are separate from the stored vectors, so no query finds itself as a trivial match.
import time
import faiss
import numpy as np
d, n, nq, k = 64, 10000, 100, 10
rng = np.random.default_rng(0)
xb = rng.normal(size=(n, d)).astype("float32")
xq = rng.normal(size=(nq, d)).astype("float32")
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)
def recall_at_k(approx_ids, exact_ids):
hits = [len(set(a) & set(t)) for a, t in zip(approx_ids, exact_ids)]
return float(np.mean(hits)) / exact_ids.shape[1]
for ef in (10, 32, 128, 512):
hnsw.hnsw.efSearch = ef
start = time.perf_counter()
_, ann_ids = hnsw.search(xq, k)
ms_per_query = (time.perf_counter() - start) * 1000 / nq
print(f"efSearch={ef:4d} recall@{k}={recall_at_k(ann_ids, true_ids):.3f} "
f"{ms_per_query:.3f} ms/query")Exact numbers depend on your machine and library version. The pattern should not change. Recall rises as efSearch rises, and latency rises with it. Random Gaussian vectors in 64 dimensions have no cluster structure, so they are harder for ANN indexes than real embeddings. Expect lower recall here than on real data at the same settings.
The recall and latency curve
Every ANN index exposes at least one search-time knob that moves you along a curve:
| Index family | Search-time knob | Raising it gives |
|---|---|---|
| HNSW | `efSearch` | Higher recall, slower queries |
| IVF | `nprobe` (clusters visited) | Higher recall, slower queries |
| Quantized indexes | Re-rank depth (exact re-scoring of the best candidates) | Higher recall, slower queries |
The curve flattens near the top. Going from recall 0.80 to 0.95 may cost twice the latency. Going from 0.95 to 0.99 may cost five times more. Pick the point where extra recall stops being worth the latency, and decide it with data from your own queries.
Build-time parameters, such as HNSW's M and efConstruction, shift the whole curve. A better-built index reaches the same recall at lower latency, but it costs more memory and indexing time. Search-time knobs can be changed per query. Build-time knobs require rebuilding the index.
Common errors when measuring recall
Using your stored vectors as queries
If a query is itself in the index, its nearest neighbor is itself at distance 0, and almost any index finds that easily. Recall looks inflated. Use held-out queries drawn from the same distribution as real traffic.
Too few queries
Recall averaged over 10 queries is noisy. Use at least a few hundred, and more if you plan to compare two configurations that differ by a point or two.
Mismatched metrics
The ground truth and the index must use the same metric. If you build the index for inner product but compute ground truth with L2 distance, recall will look poor even though nothing is wrong with the index. The same applies to normalization. If your embedding model expects cosine similarity, normalize both the stored vectors and the queries before using inner product.
Testing on a small sample
Recall at 10,000 vectors does not predict recall at 100 million. Graph and cluster structure behave differently at scale, so measure on a sample that is at least a sizeable fraction of the real collection, and re-measure when it grows.
Ignoring the tail
Average recall hides queries that do badly. A configuration with mean recall 0.95 can have 5% of queries at 0.5. Look at the distribution, for example the 5th percentile of per-query recall.
Where the loss comes from
ANN indexes lose recall in a few distinct ways, and knowing which one applies helps you tune.
- Navigation errors. Graph and cluster indexes follow a route toward the query. If the route enters the wrong region, true neighbors are never examined. Wider search (
efSearch,nprobe) reduces this. - Boundary effects. In cluster-based indexes, a query near the boundary between two clusters may have neighbors in the cluster it does not visit.
- Compression error. If vectors are stored in compressed form, the distances used to rank candidates are estimates. Re-ranking the best candidates with the original vectors repairs most of this.
- Filtering interactions. When a metadata filter removes many candidates after the search, fewer than k results may survive. This is covered in the chapter on filtering.
What to do in practice
- Build an exact baseline on a sample of your real data. Use a vector library's flat index or the brute-force code from the previous chapter.
- Choose held-out queries, a value of k that matches what your application retrieves, and a recall target.
- Sweep the search-time knob and record recall and latency for each setting, as in the script above.
- Pick the cheapest setting that meets the target at the tail percentile you care about, not only the mean.
- Repeat the check after the data grows, the embedding model changes, or you change index parameters.
Exercise
An index returns these ids for one query with k = 5: [4, 9, 12, 7, 30]. The exact top 5 is [9, 4, 7, 15, 12]. What is recall@5 for this query? Then name two things that would make a recall number measured on this setup misleading.
Show answer
The overlap is {4, 9, 12, 7}, which is 4 ids, so recall@5 = 4/5 = 0.8. Order does not matter, so the different ordering has no effect. The number could be misleading if the queries were taken from the stored vectors (each query finds itself, inflating recall), if too few queries were used (high variance), if ground truth used a different metric or normalization than the index, or if it was measured on a much smaller sample than the production collection.