Sub topic 13
Approximate nearest neighbour search at scale
This chapter assumes you know exact k-NN, the brute-force, KD-tree and ball-tree search methods, and the curse of dimensionality from earlier chapters. You should also be comfortable with NumPy and with scikit-learn's NearestNeighbors. Here you will see why exact search stops working at large scale, how approximate methods trade a little accuracy for a lot of speed, and how to measure that trade.
Why exact search runs out of road
Brute-force k-NN compares the query with every stored point. For n points in d dimensions, one query costs O(n·d) operations. A KD-tree or ball tree can reduce this to roughly O(log n) in low dimensions. As d grows, the curse of dimensionality makes distances to all points nearly equal, so the trees cannot prune branches. In practice they visit most of the data and become no faster than brute force. A common rule of thumb is that tree structures stop paying off beyond about 10 to 20 dimensions, though this depends heavily on how the data is structured.
Three pressures push real systems past exact search:
- Latency. A recommender or search service may need an answer in a few milliseconds.
- Dataset size. Embedding collections often hold millions or billions of vectors, with 128 to 1536 dimensions each.
- Memory. Storing 100 million vectors of 768
float32values takes about 300 GB before any index overhead.
Approximate nearest neighbour (ANN) search gives up the guarantee of returning the true k nearest points. It returns points that are probably among the nearest, and it does so much faster.
What "approximate" means: recall
The standard quality measure is recall@k. For each query, take the true k nearest neighbours from an exact search and the k neighbours your ANN index returned. Recall@k is the fraction of the true neighbours that the index found, averaged over queries.
recall@k = |returned ∩ true| / kA recall of 0.95 means that on average 95% of the true top-k points are in the answer. Every ANN method has a tuning knob that moves along a curve: higher recall costs more time per query. Choosing a method means choosing a point on that curve that your application can accept.
Approximation matters less for k-NN prediction than you might expect. A classifier voting over 10 neighbours often gives the same label even when one or two of the true neighbours are missed. A retrieval system returning "the top 10 most similar documents" is also usually fine with a near miss. You should still measure the effect on your own metric (accuracy, click rate, and so on) and not assume it is harmless.
Main families of ANN methods
| Family | Idea | Typical examples | Strengths | Weaknesses |
|---|---|---|---|---|
| Inverted file (IVF) | Cluster the data. Search only the clusters nearest the query. | Faiss `IndexIVFFlat` | Simple, fast to build, easy to tune | Recall drops if the true neighbour sits in an unvisited cluster |
| Graph-based | Link each point to nearby points. Walk the graph towards the query. | HNSW (hnswlib, Faiss, many vector databases) | Excellent recall/speed trade-off | High memory use, slow inserts and no easy deletes in some libraries |
| Hashing (LSH) | Hash points so that similar points often collide in the same bucket. | Random-projection LSH | Strong theory, cheap lookups | Needs many hash tables for high recall, so it often loses to graphs in practice |
| Tree forests | Build several random-split trees and search them together. | Annoy | Memory-mapped indexes, simple to deploy | Lower recall than HNSW at the same speed |
| Compression (quantization) | Store compact codes instead of full vectors. | Product quantization (PQ), ScaNN | Cuts memory by 10 to 100 times | Distances become estimates, which lowers recall |
Production systems often combine these. A common recipe is IVF to narrow the search, PQ to compress the vectors, and a final exact re-ranking of the top few hundred candidates.
How an inverted file index works
IVF is the easiest ANN method to understand, and its core idea appears in many systems.
- Build. Run k-means on the data to get
n_listscentroids. Assign every point to its nearest centroid. Each centroid owns a list of its points. - Query. Compute the distance from the query to every centroid. This is only
n_listsdistances. Choose then_probeclosest centroids. - Search. Compute exact distances only for the points in those
n_probelists. Return the best k.
If the data has 20,000 points, 100 lists and n_probe = 5, each query scans about 5% of the data plus 100 centroid distances.
The failure mode follows directly from the design. If a true neighbour lies just across a cluster boundary, it belongs to a list you did not probe, and you miss it. Raising n_probe fixes this at the cost of scanning more points.
Implementing IVF and measuring recall
The following example builds an IVF index with scikit-learn's KMeans. It compares the results with exact search and reports recall@10 for several n_probe values.
import time
import numpy as np
from sklearn.cluster import KMeans
from sklearn.neighbors import NearestNeighbors
rng = np.random.default_rng(0)
X = rng.normal(size=(20000, 32)).astype(np.float32)
queries = rng.normal(size=(100, 32)).astype(np.float32)
k = 10
# Ground truth from exact brute-force search
exact = NearestNeighbors(n_neighbors=k, algorithm="brute").fit(X)
_, true_idx = exact.kneighbors(queries)
# Build the index: cluster the data, then store one list of point ids per cluster
n_lists = 100
km = KMeans(n_clusters=n_lists, n_init=1, random_state=0).fit(X)
lists = [np.where(km.labels_ == c)[0] for c in range(n_lists)]
def ivf_search(q, k, n_probe):
# Rank centroids by distance to the query and keep the closest n_probe
d_centroids = np.linalg.norm(km.cluster_centers_ - q, axis=1)
probe = np.argsort(d_centroids)[:n_probe]
# Exact distances, but only for points in the probed lists
candidates = np.concatenate([lists[c] for c in probe])
d = np.linalg.norm(X[candidates] - q, axis=1)
return candidates[np.argsort(d)[:k]]
for n_probe in [1, 5, 10, 20, 50]:
start = time.perf_counter()
hits = 0
for q, truth in zip(queries, true_idx):
found = ivf_search(q, k, n_probe)
hits += len(set(found) & set(truth))
elapsed = time.perf_counter() - start
recall = hits / (len(queries) * k)
print(f"n_probe={n_probe:>2} recall@{k}={recall:.2f} time={elapsed:.3f}s")Exact numbers vary by machine and library version, but you should see two patterns. Recall rises as n_probe rises, and total time rises with it. Recall may also look low for small n_probe. The data here is random Gaussian noise in 32 dimensions, with no cluster structure, which is close to the worst case for any partitioning method. This is the curse of dimensionality showing up again. Real embeddings usually have more structure, so the same index gives better recall.
Two caveats apply to this teaching implementation. It loops over queries in Python and uses NumPy for each step, so its timing says little about production speed. Libraries such as Faiss run the same algorithm in optimised C++ with batching. Also, a speed comparison against algorithm="brute" in scikit-learn is not a fair test of the idea at this small scale. Both approaches are fast on 20,000 points.
Graph-based search with HNSW
HNSW (Hierarchical Navigable Small World) is the most widely used ANN method for in-memory vector search. It builds a graph in which each point is connected to a handful of near neighbours. It stacks several layers, with sparse "express" layers on top. A query enters at the top layer, greedily moves to the neighbour closest to the query, drops down a layer and repeats. At the bottom layer it explores a candidate list of size ef and returns the best k.
Its main parameters are:
M: the number of links per point. Larger values raise recall and memory use.ef_construction: how thorough the search is while building. Larger values give a better graph and a slower build.ef(query time): the size of the candidate list. Larger values raise recall and latency. It must be at least k.
# pip install hnswlib
import hnswlib
import numpy as np
rng = np.random.default_rng(0)
data = rng.random((10000, 32), dtype=np.float32)
queries = rng.random((5, 32), dtype=np.float32)
index = hnswlib.Index(space="l2", dim=32)
index.init_index(max_elements=10000, ef_construction=200, M=16)
index.add_items(data, np.arange(10000))
index.set_ef(50) # query-time breadth; must be >= k
labels, distances = index.knn_query(queries, k=5)
print(labels.shape, distances.shape) # (5, 5) (5, 5)Note that hnswlib reports squared Euclidean distance for space="l2". Take a square root if you need the actual distance.
Choosing a method
Use these criteria in roughly this order:
- Do you need ANN at all? Under about 100,000 points, exact brute force with vectorised code is often fast enough, and it removes the recall question. Try it first.
- Does the index fit in RAM? If not, use compression (PQ) or a disk-based index.
- How often does the data change? Graph indexes and IVF indexes handle bulk builds well. Heavy insert and delete workloads need a library that supports them, or periodic rebuilds.
- What recall do you need? Measure recall@k against exact search on a held-out sample of queries. Pick the cheapest setting that meets your target.
- Which distance? Check that the library supports your metric. For cosine similarity, a common approach is to normalise vectors to unit length and use inner product or Euclidean distance, which gives the same ranking.
Common mistakes
- Tuning without ground truth. Without an exact search on a sample, you cannot know your recall. Always keep a small exact baseline.
- Evaluating on the training points. If queries are also in the index, the closest neighbour is the query itself at distance zero. Query with points that are not in the index, or drop the first result.
- Forgetting that scaling still matters. ANN methods search for neighbours under a distance. Unscaled features distort that distance exactly as they do in exact k-NN. Scale or normalise before indexing.
- Reading recall as accuracy. Recall measures agreement with exact k-NN, not whether the predictions are right. An approximate index with recall 0.9 can score the same downstream accuracy as an exact one, or slightly lower. Test it.
- Rebuilding the index on every deploy without a version check. The index depends on the exact vectors and metric used to build it. If your embedding model changes, rebuild the index.
Summary
Exact search stays accurate but cost grows with the dataset, and trees stop helping in high dimensions. ANN methods narrow the search with clusters (IVF), graphs (HNSW), hashes or compressed codes, and give up a small, measurable part of recall in return. Choose the cheapest configuration that meets a recall target measured against exact search on your own data.
Exercise
In the IVF example, you raise nprobe from 5 to 50 and recall@10 goes from 0.30 to 0.85, but query time grows about tenfold. A colleague says the index is "broken" because recall is below 1.0 even at nprobe=50. What is a more accurate explanation, and what two things could you do to reach a higher recall at lower cost?
Show answer
The index is working as designed. IVF only scans the lists it probes, so any true neighbour in an unprobed list is missed, and recall below 1.0 is expected until all lists are probed (at which point the search is exact and no faster than brute force). The cost grows with nprobe because more points are scanned. To improve the trade-off, you could (1) tune nlists, since more and smaller lists give finer partitions and lower scan cost per probe, though centroid comparison cost rises, and (2) use data with more structure, for example by indexing learned embeddings instead of raw noisy features. Another valid option is to switch to a graph index such as HNSW, which usually has a better recall/latency curve at this scale.
Exercise
You index 5 million 256-dimensional float32 vectors and use the first 1,000 of them as test queries, searching the same index. Recall@1 comes out at 0.99. Why is this number misleading, and how would you fix the evaluation?
Show answer
Each query vector is itself in the index, so its nearest neighbour at distance zero is easy to find, and recall@1 is inflated. Hold the test queries out of the index (build the index from the remaining vectors), compute ground truth for those queries with exact search, and measure recall@k against it. Alternatively, keep them in the index but drop the self-match and evaluate recall@k on the remaining results.