Vector Search — Exact and Approximate Nearest Neighbours
The complexity of exact search, why tree methods fail in high dimension, and the mathematics of LSH, IVF, product quantisation and HNSW.
Exact search
For vectors in , brute-force search costs time per query and space, with no preprocessing. Every known data structure achieving query time for exact nearest neighbour in the worst case uses space exponential in or is no better than brute force once .
Consider a -d tree or any partition of into cells, with pruning based on the rule "skip a cell whose bounding box is farther than the current best distance ". If the data is i.i.d. with independent coordinates, then by distance concentration all distances lie in a window of width around , so
and the ball of radius around the query intersects essentially every cell. Pruning eliminates nothing and the search degenerates to brute force.
Key idea
This is the sharpest form of the curse of dimensionality for search: it is not that trees are slow, it is that the pruning criterion becomes vacuous. Once exact search is hopeless, the only way forward is to relax the problem, and every method below relaxes it in one of two ways: return an approximately-nearest neighbour (-ANN), or return the true nearest neighbour with probability less than one.
Locality-sensitive hashing
A family of hash functions is -sensitive for a distance if for drawn uniformly from ,
with . The exponent is .
Let for . Then for any non-zero ,
Key idea
The collision probability is , a monotone function of the angle. Combined with the cosine geometry, that makes SimHash the natural LSH family for cosine retrieval: it hashes by direction only, which is exactly what cosine similarity measures. A single bit costs one inner product, and bits give a -bit sketch whose Hamming distance estimates the angle unbiasedly with variance .
Concatenate independent hashes into (an AND, requiring all to match) and build independent tables (an OR, accepting a match in any). Then
- a near pair collides in a given table with probability , hence in some table with probability ;
- a far pair collides in a given table with probability , so the expected number of far candidates examined is .
Choosing and with gives query time and constant success probability, with space .
IVF and product quantisation
Cluster the vectors into Voronoi cells by -means. At query time, compute distances to the centroids, select the nearest cells, and search only those. Expected cost per query:
minimised over at , giving .
Split into contiguous sub-vectors of dimension and quantise each with its own codebook of centroids. Then
- storage is bits per vector, independent of — for , that is bytes, a compression of a -dimensional float32 vector;
- the squared error decomposes as ;
- the codebook has centroids representing distinct quantised points.
Key idea
Product quantisation gets representable points from stored ones. At that is points from centroids. And asymmetric distance computation — quantising only the database, keeping the query exact — lets the distance to every code be read from precomputed lookup tables of entries, so a distance evaluation is table lookups and additions rather than multiplications. That is the actual source of the speedup; the compression is what makes the index fit in memory.
HNSW
Build a multi-layer proximity graph. Each vector is inserted at a random level ; at each level it is connected to its approximate nearest neighbours among nodes present at that level. Search starts at the top (sparsest) layer, greedily descends to the closest node, then drops a layer and repeats, finishing with a best-first search at layer maintaining a candidate list of size .
Empirical observation — a regularity seen in experiments. No theorem on this page establishes it in general.
HNSW is the default index in most production vector databases and dominates ANN benchmarks at high recall. It has no proof of its recall or query complexity on general data.
What this does not say
The heuristic justification is the small-world argument: a graph with short-range links (for accuracy) and long-range links (for navigation) has greedy routing, by analogy with Kleinberg's navigable small-world results. That analogy is not a proof for HNSW: Kleinberg's theorems are about specific lattice-plus-power-law-link constructions, and HNSW's links come from the data's own geometry.
What is actually known:
- No recall guarantee. There is no bound of the form "HNSW with parameters achieves recall ", for any nontrivial data assumption.
- Adversarial failure is possible and observed. Greedy graph search can get trapped in a local minimum of the distance function; clustered data with a query between clusters is a realistic hard case.
- Construction is empirically, not provably, and is expensive in absolute terms; the index is also awkward to update and delete from.
- LSH has guarantees but loses on benchmarks. This is the honest tension: the method with theory is not the method people use, and the method people use has no theory.
So recall is measured, not proved, and measured on the specific corpus and query distribution. A recall figure from a public benchmark does not transfer to a different corpus.
Let a retrieval pipeline consist of stages with recall — where is the probability that stage passes on the relevant document given that it received it. Then the end-to-end recall is , and in particular is at most .
Key idea
This is the most consequential and most ignored fact about RAG system design. A cross-encoder reranker cannot recover a document the ANN index did not return: if the index has recall , the system's ceiling is however good the reranker is. Tuning the reranker while the index silently drops of relevant documents is effort spent on the wrong stage.
The same multiplicative structure propagates into generation, quantified on the latent-variable page: retrieval failure is not a soft degradation but a hard ceiling on the information available to the model.
Comparison
| Method | Query time | Space | Guarantee | Metric |
|---|---|---|---|---|
| Brute force | exact | any | ||
| LSH (SimHash) | -ANN with probability | cosine | ||
| IVF | none | , inner product | ||
| IVF + PQ | as IVF, smaller constant | bytes | none | , inner product |
| HNSW | empirical | links | none | , cosine, inner product |
Problems
Why space-partitioning trees fail in high dimensionProof · Advanced · 30 min The random-hyperplane collision probabilityProof · Intermediate · 30 min The LSH amplification exponentProof · Graduate · 1 hour Product quantisation budget arithmeticNumerical · Beginner · 30 min Recall composes multiplicativelyNumerical · Beginner · 15 min Implement SimHash LSH and measure recallCoding · Advanced · 3 hoursReferences
- PaperPiotr Indyk and Rajeev Motwani (1998). Approximate Nearest Neighbors — Towards Removing the Curse of Dimensionality
- PaperMoses S. Charikar (2002). Similarity Estimation Techniques from Rounding Algorithms
- PaperHervé Jégou, Matthijs Douze and Cordelia Schmid (2011). Product Quantization for Nearest Neighbor Search
- PaperYury A. Malkov and Dmitry A. Yashunin (2018). Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs
- SurveyAlexandr Andoni, Piotr Indyk and Ilya Razenshteyn (2018). Approximate Nearest Neighbor Search in High Dimensions
These works are cited as sources to read, not reproduced. All exposition, examples and problems on this site are written independently; where an argument is standard, the citation points to a canonical treatment.
Results stated on this page
- PropositionCost of exact nearest-neighbour searchproof includedBrute force is N d per query with no preprocessing; no known method achieves both sublinear query time and subexponential space in high dimension.
- PropositionWhy space-partitioning trees fail in high dimensionproof includedPruning requires the query ball to miss most cells, and concentration of distances makes that impossible once the dimension exceeds log of the number of points.
- DefinitionLocality-sensitive hash familyA hash family whose collision probability decreases with distance, with a gap parameter that determines the achievable exponent.
- TheoremRandom-hyperplane LSH collision probabilityproof includedThe probability that a random hyperplane separates two vectors is their angle divided by pi.
- PropositionAND/OR amplification and the LSH exponentproof includedConcatenating k hashes and using L tables turns the collision gap into a sublinear query exponent.
- PropositionProduct quantisation error and compressionproof includedSplitting the vector into m subspaces with 256 centroids each gives m bytes per vector and an error that is the sum of subspace quantisation errors.
- Empirical observationHNSW has no worst-case guaranteeThe dominant ANN index in practice is justified by benchmarks and a small-world heuristic, not by a theorem about its recall.
- PropositionRecall composes multiplicatively through a pipelineproof includedA retrieval stage's recall bounds everything downstream, so a 0.9-recall index caps the whole system at 0.9 regardless of the reranker.
Problems (6)
All problems- Implement SimHash LSH and measure recallCodingAdvanced⏱ 3 hours
- The LSH amplification exponentProofGraduate⏱ 1 hour
- Product quantisation budget arithmeticNumericalBeginner⏱ 30 min
- Recall composes multiplicativelyNumericalBeginner⏱ 15 min
- The random-hyperplane collision probabilityProofIntermediate⏱ 30 min
- Why space-partitioning trees fail in high dimensionProofAdvanced⏱ 30 min