Skip to content
nonconvexcard

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.

RAGGraduate⏱ 1 day11 min readannnearest neighbour searchlshivfproduct quantisation
6 problems →
PropositionCost of exact nearest-neighbour search

For NN vectors in Rd\R^d, brute-force search costs O(Nd)O(Nd) time per query and O(Nd)O(Nd) space, with no preprocessing. Every known data structure achieving query time o(N)o(N) for exact nearest neighbour in the worst case uses space exponential in dd or is no better than brute force once d=Ω(log⁡N)d = \Omega(\log N).

PropositionWhy space-partitioning trees fail in high dimension

Consider a kk-d tree or any partition of Rd\R^d into cells, with pruning based on the rule "skip a cell whose bounding box is farther than the current best distance rr". If the data is i.i.d. with independent coordinates, then by distance concentration all NN distances lie in a window of width O(log⁡N)O(\sqrt{\log N}) around 2d\sqrt{2d}, so

rtypical distance→1,\frac{r}{\text{typical distance}} \to 1 ,

and the ball of radius rr 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 (cc-ANN), or return the true nearest neighbour with probability less than one.

Locality-sensitive hashing

DefinitionLocality-sensitive hash family

A family H\mathcal{H} of hash functions is (r,cr,p1,p2)(r, cr, p_1, p_2)-sensitive for a distance ρ\rho if for hh drawn uniformly from H\mathcal{H},

ρ(u,v)≤r  ⟹  P(h(u)=h(v))≥p1,ρ(u,v)≥cr  ⟹  P(h(u)=h(v))≤p2,\rho(u,v)\le r \implies \P\big(h(u)=h(v)\big)\ge p_1, \qquad \rho(u,v)\ge cr \implies \P\big(h(u)=h(v)\big)\le p_2,

with p1>p2p_1>p_2. The exponent is ϱ=log⁡(1/p1)log⁡(1/p2)∈(0,1)\varrho = \dfrac{\log(1/p_1)}{\log(1/p_2)} \in (0,1).

TheoremRandom-hyperplane LSH collision probability

Let hw(u)=sign⁡⟨w,u⟩h_w(u) = \sign\ip wu for w∼N(0,Id)w\sim\Ncal(0,I_d). Then for any non-zero u,vu,v,

P(hw(u)≠hw(v))=θ(u,v)π,θ(u,v)=arccos⁡⟨u,v⟩∥u∥∥v∥.\P\big(h_w(u)\ne h_w(v)\big) = \frac{\theta(u,v)}{\pi}, \qquad \theta(u,v) = \arccos\frac{\ip uv}{\norm u\norm v} .

Key idea

The collision probability is 1−θ/π1 - \theta/\pi, 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 bb bits give a bb-bit sketch whose Hamming distance estimates the angle unbiasedly with variance O(1/b)O(1/b).

PropositionAND/OR amplification and the LSH exponent

Concatenate kk independent hashes into g=(h1,…,hk)g = (h_1,\dots,h_k) (an AND, requiring all to match) and build LL independent tables (an OR, accepting a match in any). Then

  • a near pair collides in a given table with probability p1kp_1^k, hence in some table with probability 1−(1−p1k)L1-(1-p_1^k)^L;
  • a far pair collides in a given table with probability p2kp_2^k, so the expected number of far candidates examined is LNp2kLNp_2^k.

Choosing k=log⁡1/p2Nk = \log_{1/p_2}N and L=NϱL = N^{\varrho} with ϱ=log⁡(1/p1)/log⁡(1/p2)\varrho = \log(1/p_1)/\log(1/p_2) gives query time O~(Nϱ)\tilde O(N^\varrho) and constant success probability, with space O~(N1+ϱ)\tilde O(N^{1+\varrho}).

IVF and product quantisation

DefinitionInverted file index (IVF)

Cluster the NN vectors into nlistn_{\text{list}} Voronoi cells by kk-means. At query time, compute distances to the nlistn_{\text{list}} centroids, select the nproben_{\text{probe}} nearest cells, and search only those. Expected cost per query:

O ⁣(nlistd+nprobenlistNd),O\!\left(n_{\text{list}}d + \frac{n_{\text{probe}}}{n_{\text{list}}}Nd\right),

minimised over nlistn_{\text{list}} at nlist≍Nnproben_{\text{list}}\asymp\sqrt{N n_{\text{probe}}}, giving O(Nnprobe d)O(\sqrt{Nn_{\text{probe}}}\,d).

PropositionProduct quantisation error and compression

Split x∈Rdx\in\R^d into mm contiguous sub-vectors of dimension d/md/m and quantise each with its own codebook of 2b2^b centroids. Then

  • storage is mbmb bits per vector, independent of dd — for m=8m=8, b=8b=8 that is 88 bytes, a 384×384\times compression of a 768768-dimensional float32 vector;
  • the squared error decomposes as ∥x−x^∥22=∑j=1m∥x(j)−x^(j)∥22\norm{x-\hat x}_2^2 = \sum_{j=1}^m\norm{x^{(j)} - \hat x^{(j)}}_2^2;
  • the codebook has m2bm2^b centroids representing 2mb2^{mb} distinct quantised points.

Key idea

Product quantisation gets 2mb2^{mb} representable points from m2bm2^b stored ones. At m=8,b=8m=8,b=8 that is 2642^{64} points from 20482048 centroids. And asymmetric distance computation — quantising only the database, keeping the query exact — lets the distance to every code be read from mm precomputed lookup tables of 2b2^b entries, so a distance evaluation is mm table lookups and additions rather than dd multiplications. That is the actual source of the speedup; the compression is what makes the index fit in memory.

HNSW

DefinitionHierarchical navigable small world graph

Build a multi-layer proximity graph. Each vector is inserted at a random level ℓ∼⌊−log⁡U/log⁡M⌋\ell\sim\lfloor-\log U/\log M\rfloor; at each level it is connected to its approximate MM 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 00 maintaining a candidate list of size efSearch\mathrm{efSearch}.

Empirical observationHNSW has no worst-case guarantee

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 O(log⁡N)O(\log N) 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 (M,efSearch)(M,\mathrm{efSearch}) achieves recall ≥1−δ\ge1-\delta", 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 O(Nlog⁡N)O(N\log N) 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.

PropositionRecall composes multiplicatively through a pipeline

Let a retrieval pipeline consist of stages with recall γ1,…,γm\gamma_1,\dots,\gamma_m — where γi\gamma_i is the probability that stage ii passes on the relevant document given that it received it. Then the end-to-end recall is ∏iγi\prod_i\gamma_i, and in particular is at most min⁡iγi\min_i\gamma_i.

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 0.90.9, the system's ceiling is 0.90.9 however good the reranker is. Tuning the reranker while the index silently drops 10%10\% 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

MethodQuery timeSpaceGuaranteeMetric
Brute forceO(Nd)O(Nd)O(Nd)O(Nd)exactany
LSH (SimHash)O~(Nϱ)\tilde O(N^{\varrho})O~(N1+ϱ)\tilde O(N^{1+\varrho})cc-ANN with probabilitycosine
IVFO(Nnprobed)O(\sqrt{Nn_{\text{probe}}}d)O(Nd)O(Nd)noneℓ2\ell^2, inner product
IVF + PQas IVF, smaller constantO(Nmb/8)O(Nmb/8) bytesnoneℓ2\ell^2, inner product
HNSWO(log⁡N)O(\log N) empiricalO(NM)O(NM) links +O(Nd)+ O(Nd)noneℓ2\ell^2, 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 hours

References

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

Problems (6)

All problems

Papers that use this mathematics