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 , where each is a vector in , and let be the query. The most common distance is the Euclidean distance, which is the norm of the difference:
Here is the length of (see vector norm). The exact answer requires computing all distances.
Recall
An ANN method returns a set of candidates. Its quality is measured by recall at : the fraction of the true nearest neighbors that the method found.
A recall of 0.9 at 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 , expand the square:
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.
Graph search
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 and repeats one step: among the neighbors of the current vertex , move to the neighbor with the smallest , and stop when no neighbor is closer than itself. The search returns . 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
Take eight points in the plane and the query . Use squared distances, which give the same ranking.
| Point | Coordinates | Squared 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 |
- The exact nearest neighbor is F, with squared distance 0.5.
- Build a graph with edges A-B, B-C, C-D, D-E, E-F, F-G, G-H and one shortcut A-H.
- Start the greedy walk at A, distance 22.5. Its neighbors are B (14.5) and H (6.5). Move to H.
- H has neighbors G (22.5) and A (22.5). Both are farther than H, so the walk stops at H.
- 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.
This is an illustrative calculation with round numbers, not a measured benchmark.
- Corpus: vectors of dimension .
- Exact search per query: multiply-adds.
- Suppose a graph search visits about vectors before it stops. Its cost is multiply-adds, plus the cost of walking the graph.
- The ratio is .
- 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
| Situation | What goes wrong | Better choice |
|---|---|---|
| Small collection, say a few thousand vectors | An index adds build time and complexity for little gain | Exact search with a matrix multiply |
| Results must be exactly correct, for example a legal or safety lookup | Missed neighbors are unacceptable | Exact search, or ANN followed by an exact re-rank of the candidates |
| Data changes constantly | Some graph and tree indexes degrade or need rebuilding after many inserts and deletes | Indexes that support incremental updates, or periodic rebuilds |
| Vectors are very high-dimensional and random | Space partitioning trees stop pruning, because every region overlaps the query's neighborhood | Graph-based search, or quantized vectors that shrink the cost of each distance |
| Memory is tight | Full-precision vectors plus a graph can exceed RAM | Quantization (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 items | Use 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 vectors of dimension . How many multiply-adds does one exact query need?Show answer
Each distance computation is about multiply-adds, and an exact search computes one per stored vector. The total is 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 , 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.