Search

Search papers and lessons

Approximate Nearest Neighbor Search

Level 3 · 9 min read

Approximate nearest neighbor search finds vectors that are very likely the closest to a query by skipping most of the data, trading a few missed results for a large speedup.

On this page

  • Colour = topic mix
  • Discrete math
  • Linear algebra
  • Algorithms
  • Sign in to see your progress

TL;DR

Given a query vector and a large collection of stored vectors, nearest neighbor search asks which stored vector is closest to the query. Doing this exactly means measuring the distance to every stored vector, which gets too slow when there are millions of them. Approximate nearest neighbor (ANN) search builds an index that lets it look at only a small part of the collection, and accepts that it will sometimes return the second or tenth closest vector instead of the first.

Where you'll see it: semantic search over document embeddings, image and face lookup, recommendation candidate generation, and the retrieval step of retrieval-augmented generation.

Intuition

Finding the nearest shop on a map

Suppose you stand in a city of a million shops and want the one closest to you. The exact way is to measure the distance to each shop and keep the smallest. That is always correct and always takes a million measurements.

A faster way uses roads. You do not need to check shops on the other side of the city. Start at any shop, look at its nearby connections, step to whichever neighbor is closer to you, and repeat. You will usually end near the right shop after visiting a few dozen places. Sometimes you will stop at a shop that is a block away from the true best, because the road network had no short path from where you were. You traded a small chance of being slightly wrong for a huge saving in walking.

ANN search works the same way. The "roads" are a graph built over the stored vectors, or a tree or set of buckets that groups nearby vectors together. The search walks along these structures toward the query.

flowchart LR
    S[Start at entry vertex] --> N{Any neighbor closer to the query?}
    N -- yes --> M[Move to the closest neighbor]
    M --> N
    N -- no --> R[Return current vertex]

Why exact search stops scaling

Take a corpus of one million documents, each turned into a 768-dimensional embedding. Exact search computes one dot product of length 768 per document. The work per query grows linearly with the number of stored vectors, and every query repeats it. Once the corpus is large and queries arrive many times per second, the linear scan is the bottleneck. ANN search aims to make the work per query grow much more slowly, close to the logarithm of the collection size, while losing only a small fraction of the true neighbors.

The math

Let the stored set be X={x1,…,xn}X = \{\mathbf{x}_1, \dots, \mathbf{x}_n\}, where each xi\mathbf{x}_i is a vector in Rd\mathbb{R}^d, and let q\mathbf{q} be the query. The most common distance is the Euclidean distance, which is the norm of the difference:

Definition: Exact nearest neighbor
x⋆=arg⁡min⁡x∈X∥x−q∥2,∥v∥2=v12+⋯+vd2\mathbf{x}^\star = \arg\min_{\mathbf{x} \in X} \lVert \mathbf{x} - \mathbf{q} \rVert_2, \qquad \lVert \mathbf{v} \rVert_2 = \sqrt{v_1^2 + \cdots + v_d^2}

Here ∥v∥2\lVert \mathbf{v} \rVert_2 is the length of v\mathbf{v} (see vector norm). The exact answer requires computing all nn distances.

Recall

An ANN method returns a set K^\hat{K} of kk candidates. Its quality is measured by recall at kk: the fraction of the true kk nearest neighbors KK that the method found.

recall@k=∣K^∩K∣k\text{recall@}k = \frac{|\hat{K} \cap K|}{k}

A recall of 0.9 at k=10k = 10 means that on average nine of the ten true neighbors were returned. Recall is the knob that connects accuracy to speed: searching more of the index raises recall and costs more time.

Unit vectors turn distance into angle

Many embeddings are normalized to length 1. For unit vectors ∥x∥2=∥q∥2=1\lVert \mathbf{x} \rVert_2 = \lVert \mathbf{q} \rVert_2 = 1, expand the square:

∥x−q∥22=∥x∥22+∥q∥22−2 x⋅q=2−2 x⋅q\lVert \mathbf{x} - \mathbf{q} \rVert_2^2 = \lVert \mathbf{x} \rVert_2^2 + \lVert \mathbf{q} \rVert_2^2 - 2\, \mathbf{x}\cdot\mathbf{q} = 2 - 2\,\mathbf{x}\cdot\mathbf{q}

So for unit vectors, the nearest point in Euclidean distance is the one with the largest dot product, which is the same as the largest cosine similarity. Ranking by one is ranking by the other, so an index built for one serves both.

Most modern ANN indexes connect each stored vector to a few others that are close to it, forming a proximity graph (see graph). Greedy search starts at an entry vertex v0v_0 and repeats one step: among the neighbors of the current vertex vv, move to the neighbor uu with the smallest ∥u−q∥2\lVert \mathbf{u} - \mathbf{q} \rVert_2, and stop when no neighbor is closer than vv itself. The search returns vv. Each step computes only as many distances as the vertex has neighbors, so the total work is the number of vertices visited times the degree.

Greedy search can stop at a local minimum, a vertex closer to the query than all its neighbors but not the true nearest point. Keeping a list of several candidates, not just one, and expanding more of them reduces this risk at the cost of more distance computations.

Worked examples

Example
A greedy walk that gets stuck

Take eight points in the plane and the query q=(4.5,1.5)\mathbf{q} = (4.5, 1.5). Use squared distances, which give the same ranking.

PointCoordinatesSquared distance to q
A(0, 0)22.5
B(1, 0)14.5
C(2, 1)6.5
D(3, 3)4.5
E(4, 0)2.5
F(5, 2)0.5
G(6, 6)22.5
H(7, 1)6.5
  1. The exact nearest neighbor is F, with squared distance 0.5.
  2. Build a graph with edges A-B, B-C, C-D, D-E, E-F, F-G, G-H and one shortcut A-H.
  3. Start the greedy walk at A, distance 22.5. Its neighbors are B (14.5) and H (6.5). Move to H.
  4. H has neighbors G (22.5) and A (22.5). Both are farther than H, so the walk stops at H.
  5. The method returns H with squared distance 6.5, which is not the true nearest neighbor. Recall at 1 is 0 for this query.

Interpretation: the shortcut A-H pulled the walk toward a point that was close to the query but on the wrong side of the chain. A search that keeps several candidates, or a graph with more edges, would have a path to F.

Example
What the savings look like at scale

This is an illustrative calculation with round numbers, not a measured benchmark.

  1. Corpus: n=106n = 10^6 vectors of dimension d=768d = 768.
  2. Exact search per query: n⋅d=106⋅768=7.68×108n \cdot d = 10^6 \cdot 768 = 7.68 \times 10^8 multiply-adds.
  3. Suppose a graph search visits about 1,0001{,}000 vectors before it stops. Its cost is 1,000⋅768=7.68×1051{,}000 \cdot 768 = 7.68 \times 10^5 multiply-adds, plus the cost of walking the graph.
  4. The ratio is 7.68×108/7.68×105=10007.68 \times 10^8 / 7.68 \times 10^5 = 1000.
  5. Interpretation: the index does about a thousandth of the arithmetic. The price is that it may miss some true neighbors, which is why recall is measured and tuned.

Tradeoffs and failure modes

SituationWhat goes wrongBetter choice
Small collection, say a few thousand vectorsAn index adds build time and complexity for little gainExact search with a matrix multiply
Results must be exactly correct, for example a legal or safety lookupMissed neighbors are unacceptableExact search, or ANN followed by an exact re-rank of the candidates
Data changes constantlySome graph and tree indexes degrade or need rebuilding after many inserts and deletesIndexes that support incremental updates, or periodic rebuilds
Vectors are very high-dimensional and randomSpace partitioning trees stop pruning, because every region overlaps the query's neighborhoodGraph-based search, or quantized vectors that shrink the cost of each distance
Memory is tightFull-precision vectors plus a graph can exceed RAMQuantization (compressed codes), with a re-rank on full vectors
The metric is not a distance (for example, inner product on unnormalized vectors)Some methods assume a metric and return the wrong itemsUse an index built for inner product, or normalize the vectors

Failure modes to check in practice: recall measured against brute force on a sample of real queries, not on random vectors; latency at the tail (p99), not only the average; and the effect of inserts on recall after the index has been running for a while.

History

Exact nearest neighbor search has a long history in computational geometry. Jon Bentley introduced the k-d tree in 1975 as a way to search multidimensional data by splitting space along one coordinate at each level. It works well in a few dimensions and loses its advantage as dimension grows.

Piotr Indyk and Rajeev Motwani showed in the late 1990s that a randomized hashing scheme, locality-sensitive hashing, could give sublinear query time for approximate search with provable guarantees. It made approximation an explicit, analyzable choice rather than a heuristic.

In the 2010s, graph-based methods became the practical default for large embedding collections. Yury Malkov and Dmitry Yashunin posted the Hierarchical Navigable Small World (HNSW) method to arXiv in 2016, which builds several layers of proximity graphs so that a search can descend coarse-to-fine. Libraries such as FAISS and Annoy made these methods widely available, and vector databases now expose them as the default index. The rise of language model embeddings in the same period made fast nearest neighbor lookup a routine need.

Check yourself

QuestionRecall, in one sentence: what does ANN search give up compared with exact search, and what does it gain?Show answer

It gives up a guarantee that the returned vectors are the true nearest neighbors, accepting that some true neighbors are missed. It gains a large reduction in the number of distances computed per query, so queries stay fast as the collection grows.

QuestionA collection holds n=2×106n = 2 \times 10^6 vectors of dimension d=384d = 384. How many multiply-adds does one exact query need?Show answer

Each distance computation is about d=384d = 384 multiply-adds, and an exact search computes one per stored vector. The total is n⋅d=2×106⋅384=7.68×108n \cdot d = 2 \times 10^6 \cdot 384 = 7.68 \times 10^8 multiply-adds per query.

QuestionWhy does a greedy graph walk sometimes return a point that is not the nearest neighbor, even when the graph is connected?Show answer

Greedy search only moves to a neighbor that is closer to the query than the current vertex. If the current vertex is closer than all of its neighbors, the walk stops, even if a better vertex exists farther along the graph. Such a vertex is a local minimum. Keeping several candidates and expanding more of them lets the search escape some local minima.

QuestionYou normalize all vectors to length 1 and then build an index for Euclidean distance. A colleague wants to use the same index for cosine similarity. Is that valid, and why?Show answer

Yes. For unit vectors, the squared Euclidean distance equals 2−2 x⋅q2 - 2\,\mathbf{x}\cdot\mathbf{q}, so the ordering by Euclidean distance is the reverse of the ordering by dot product, which equals cosine similarity for unit vectors. Both rankings agree, so the same index returns the same top results for either measure.

Sources