Nearest-Neighbor Search Explained
What a vector index is asked to do, why the similarity metric decides the ranking, what exact search costs, and how recall@k measures an approximate index against it.
Contentsand lesson path
On this page
- Why it matters
- The question a vector index answers
- Exact search and what it costs
- Approximate search and recall@k
- Check your understanding
- Apply it
- Review prompt
Lessons of Vector Search Foundations
- Nearest-Neighbor Search Explained Concept · 15 min
- Brute-Force kNN as a Baseline Worked example · 20 min
- Approximate Indexes and Their Knobs Concept · 15 min
- Lab: HNSW Recall Versus Latency Lab · 25 min
- Filters and Hybrid Search with Rank Fusion Lab · 25 min
- Check: Pick an Index for a Workload Knowledge check · 6 questions
What you will learn
- Implement exact k-nearest-neighbor search and use it as the baseline for an approximate index.
Prerequisites: Embeddings
01. Why it matters
In the Embeddings skill you turned text into vectors and compared two of them. A retrieval system has a larger job: given one query vector, find the few most similar stored vectors among thousands or millions, fast enough for a person waiting on an answer. That is nearest-neighbour search, and every RAG pipeline, semantic search box and "similar items" feature depends on it.
Whatever this step misses, later steps never see: a prompt cannot ground an answer in a passage that was not retrieved. So before choosing a vector database or tuning an index, you need a precise picture of the question the index answers, what answering it exactly costs, and how to tell how far a faster, approximate answer drifts from the exact one. The next lesson builds the exact search, and the rest of the skill measures approximate indexes against it.
02. The question a vector index answers
k-nearest-neighbour (kNN) search takes a query vector q, a collection of N stored vectors and a number k, and returns the k stored vectors that score best against q under a chosen metric, best first. In retrieval, k is small (often 5 to 50), N is large, and each vector has a few hundred to a few thousand dimensions.
Three metrics are common:
- Dot product: higher is closer. Fast, but it rewards vectors that are simply long.
- Cosine similarity: the dot product of the two vectors after scaling each to length 1, so only direction counts. Higher is closer.
- Euclidean (L2) distance: the straight-line distance. Lower is closer.
The metric decides the ranking, so it is part of the question, not a detail. The small example below ranks four stored vectors against one query, first as they are and then after scaling every vector to length 1. On unit vectors, the plain dot product is the cosine similarity, so the script computes cosine that way.
import numpy as np
docs = np.array([
[0.9, 0.1, 0.0], # A: close in direction to the query
[0.6, 0.8, 0.0], # B
[0.0, 0.6, 0.8], # C: a different direction
[2.0, 1.8, 0.0], # D: between A and B in direction, but much longer
])
query = np.array([1.0, 0.2, 0.0])
names = np.array(list("ABCD"))
def ranking(scores: np.ndarray, higher_is_better: bool = True) -> str:
order = np.argsort(-scores if higher_is_better else scores)
return " ".join(names[order])
def l2(vectors: np.ndarray, q: np.ndarray) -> np.ndarray:
return np.linalg.norm(vectors - q, axis=1)
print("raw dot product: ", ranking(docs @ query))
print("raw L2 distance: ", ranking(l2(docs, query), higher_is_better=False))
unit_docs = docs / np.linalg.norm(docs, axis=1, keepdims=True)
unit_query = query / np.linalg.norm(query)
print("cosine: ", ranking(unit_docs @ unit_query))
print("unit L2 distance:", ranking(l2(unit_docs, unit_query), higher_is_better=False))raw dot product: D A B C
raw L2 distance: A B C D
cosine: A D B C
unit L2 distance: A D B COn the raw vectors the metrics disagree. The dot product puts the long vector D first because its length inflates every score; Euclidean distance puts D last because its length puts it far away. Cosine ranks by direction alone.
Once every vector has length 1, all three agree: cosine and the dot product become the same number, and the squared distance is 2 - 2 × (a · b), so a larger dot product always means a smaller distance. This is why most pipelines normalise embeddings once, when indexing and when querying, and then use the cheapest operation, the dot product. Two rules follow:
- Use the metric your embedding model was trained for (its model card says which), and configure the index with the same one.
- If the dot product stands in for cosine, check that stored and query vectors really are unit length. One unnormalised batch silently changes the ranking.
03. Exact search and what it costs
The direct way to answer a kNN query is exact (or brute-force) search: score the query against every stored vector, then keep the k best. Its answer is correct by definition, which makes it the reference that every faster method is judged against. Its cost is easy to estimate: one query needs N × d multiply-adds, plus a pass over N scores to pick the top k, and the vectors have to sit in memory, at 4 bytes per number in float32.
vectors (N) dims (d) multiply-adds per query memory for the vectors
10,000 384 3.8 million 15 MB
1,000,000 768 768 million 3.1 GB
100,000,000 768 77 billion 307 GBThe work grows linearly with N. At ten thousand vectors a single CPU core finishes a query in about a millisecond, and the next lesson measures this on your machine. At a million 768-dimension vectors the same core needs a few hundred milliseconds per query, and at a hundred million the vectors no longer fit in the memory of a typical server.
Exact search scales further than people expect: matrix multiplication libraries use every core and vector instruction available, and scoring many queries in one batch is far cheaper than scoring them one by one. So the sensible order is to start exact, measure latency against your budget, and move to an approximate index only when the numbers say you must. Even then you keep the exact search, because it is how you will check the approximate one.
04. Approximate search and recall@k
Approximate nearest-neighbour (ANN) indexes avoid comparing the query with everything. They organise the vectors at build time so that a query visits only a promising fraction of them:
- Graph indexes such as HNSW link each vector to some of its neighbours, and a query walks the links towards the best region.
- Clustering (inverted-file, IVF) indexes group vectors around centroids, and a query scans only the nearest clusters.
- Quantisation stores compressed codes instead of full vectors, trading precision for memory; it is often combined with IVF.
Each family has settings for how much of the collection a query explores: more exploration finds more true neighbours but takes longer. Lessons 3 and 4 cover and measure them.
To measure an approximate index, compare its top k with the exact top k for the same query. Recall@k is the share of the exact top k that the index also returned. Only membership counts, not order:
exact top 5: [17, 4, 92, 33, 8]
approximate top 5: [17, 92, 4, 51, 33]
shared ids: 17, 4, 92, 33 -> recall@5 = 4 / 5 = 0.8Average it over a few hundred queries that look like real traffic, and you have one number that says how faithfully the index reproduces exact search. Then set it against latency: an index setting is only "good" relative to a recall target and a latency budget.
Be clear about what this recall measures. It compares the index with exact search over the same vectors, so it tells you nothing about whether those neighbours are relevant to the user. A perfect index over a poor embedding model still retrieves poor passages. Relevance needs labelled queries, which the RAG Retrieval Evaluation skill covers. Keep the two numbers apart and you will know which component to fix.
05. Check your understanding
06. Apply it
The practice project for this skill indexes 10,000 embeddings and measures an approximate index against exact search. Prepare its inputs now:
- Take 10,000 chunks you embedded in the Embeddings skill (or embed them now) and save the matrix as a float32
.npyfile with the chunk ids in the same order. - Write down the dimension, the metric your model's card recommends, and whether the vectors are unit length. Check the last point in code:
np.linalg.norm(vectors, axis=1)should be 1.0 everywhere if you normalised. - Collect 100 to 200 query strings that were not used to build the corpus, ideally real questions, and embed them the same way.
- Estimate the memory of the vectors and the multiply-adds per query, and write down the
kyou will retrieve and a latency budget per query.
07. Review prompt
Without looking back:
- State the kNN question in one sentence, naming its three inputs.
- Why can dot product, cosine and Euclidean distance rank the same vectors differently, and when do they always agree?
- Estimate the memory and multiply-adds for one exact query over 500,000 vectors of 1,536 dimensions in float32.
- Define recall@k for an approximate index, and say what it does not tell you about retrieval quality.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.