Sub topic 13
Approximate nearest neighbour search at scale
This chapter assumes you know how exact k-NN works, how KD-trees and ball trees speed up search, and why distances lose meaning in high dimensions. It covers what to do when exact search is still too slow.
Why exact search stops scaling
Brute force compares a query with every stored point, so one query costs O(n·d) for n points in d dimensions. KD-trees and ball trees cut this in low dimensions. In high dimensions they prune very little, and their cost drifts back toward brute force.
Suppose you have 50 million embedding vectors with 384 dimensions and need answers in a few milliseconds. Exact search cannot do that on one machine. Approximate nearest neighbour (ANN) search is a family of methods that returns neighbours that are probably the true nearest ones, in exchange for much lower query time.
The accuracy trade-off
ANN methods are judged by recall@k. This is the fraction of the true k nearest neighbours that the method actually returns. If the exact top 10 and the approximate top 10 share 9 points, recall@10 is 0.9.
You tune each method to balance three things: recall, query speed, and memory (plus index build time). Higher recall costs more time or memory. For a classifier, a missed neighbour only matters if it changes the vote, so moderate recall is often acceptable. For a retrieval system, a missed neighbour is a missing result.
Main families of ANN methods
| Family | Idea | Typical examples |
|---|---|---|
| Graph-based | Link each point to near points. Search walks the graph toward the query. | HNSW |
| Hash-based | Hash points so that similar ones land in the same bucket. Search only checks the query's bucket. | Locality-sensitive hashing (LSH) |
| Cluster-based | Group points into clusters. Search only scans the few clusters closest to the query. | IVF (inverted file index) |
| Compression-based | Store short codes in place of full vectors, which saves memory and speeds up distance computation. | Product quantization (PQ) |
Production systems often combine families, for example IVF with PQ.
How a graph index finds neighbours
HNSW (Hierarchical Navigable Small World) stacks several graph layers. The top layer has few points and long links. Lower layers have more points and shorter links. A query enters at the top, moves greedily to the node closest to it, then drops a layer and repeats. At the bottom layer it explores a small candidate list and returns the best k.
Because search follows links instead of scanning everything, query time grows roughly with the logarithm of n.
Trying it in Python
The hnswlib library implements HNSW. The parameter ef sets the candidate list size at query time. Raising it increases recall and slows queries.
import numpy as np
import hnswlib
rng = np.random.default_rng(0)
n, d = 20000, 64
data = rng.random((n, d), dtype=np.float32)
queries = rng.random((100, d), dtype=np.float32)
index = hnswlib.Index(space="l2", dim=d)
index.init_index(max_elements=n, ef_construction=200, M=16)
index.add_items(data)
index.set_ef(50)
labels, distances = index.knn_query(queries, k=5)
# Exact answer for comparison, using brute force
exact = np.argsort(
((queries[:, None, :] - data[None, :, :]) ** 2).sum(axis=2), axis=1
)[:, :5]
hits = sum(len(set(labels[i]) & set(exact[i])) for i in range(len(queries)))
print("recall@5:", hits / (len(queries) * 5))Install it with pip install hnswlib. The brute-force comparison here builds a large array, so keep the data small when you test. Try set_ef(10) and set_ef(200) and watch recall change.
Decision criteria
- Under about 100,000 points, low dimension: exact search with a KD-tree or ball tree is usually enough.
- Millions of points, high dimension: use ANN.
- Memory is the limit: use compression such as product quantization, accepting some distance error.
- Data changes constantly: check whether the index supports inserts and deletes. Some indexes must be rebuilt.
Common mistakes
- Measuring only speed. Always measure recall against an exact baseline on a sample.
- Forgetting that the metric is fixed when you build the index. Switching from Euclidean to cosine means building a new index.
- Skipping feature scaling. ANN indexes approximate the same distance, so unscaled features still distort the results.
- Tuning on queries that are unlike real traffic. Recall depends on how queries are distributed.
Exercise
An ANN index returns recall@10 of 0.80 at 2 ms per query. Name one setting change that would likely raise recall, and what it costs.
Show answer
Increase the search effort, for example a larger ef in HNSW or more clusters probed in IVF. Recall rises, but each query takes longer. Raising index build parameters such as M or ef_construction can also help, at the cost of more memory and build time.
Exercise
Why do KD-trees stop helping in very high dimensions, and what do ANN methods give up to stay fast?
Show answer
In high dimensions the distances to near and far points become similar, so the tree cannot prune many branches and ends up checking most points. ANN methods give up the guarantee of returning the exact nearest neighbours, accepting recall below 1.0 in return for speed.