Lesson 2 of 9 · Concepts
Nearest Neighbour Search
How vector databases find similar vectors: exact k-NN, cosine, dot product and Euclidean distance, approximate nearest neighbour search and measuring recall.
- 7 min read
- Intermediate
- Reviewed
- Describe exact k-nearest-neighbour search and what it costs
- Choose between cosine, dot product and Euclidean distance
- Explain what approximate nearest neighbour (ANN) search gives up, and what it gains
- Measure the quality of an approximate search with recall@k
The question every vector database answers
The simplest way is exact search: score every vector and keep the best k. Python's heapq.nlargest keeps the top k without sorting everything:
import heapq
import random
random.seed(7)
DIMS = 16
def random_vector():
return [random.uniform(-1, 1) for _ in range(DIMS)]
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
vectors = [random_vector() for _ in range(5000)]
query = random_vector()
# Exact k-nearest-neighbour search: score every vector, keep the best k.
comparisons = 0
def score(i):
global comparisons
comparisons += 1
return dot(query, vectors[i])
top5 = heapq.nlargest(5, range(len(vectors)), key=score)
print("Exact top 5 ids:", top5)
print("Comparisons:", comparisons)The answer is perfect, but the work grows with every vector you add: 5,000 vectors means 5,000 comparisons; 50 million vectors means 50 million.
Measuring “closeness”
Vector databases ask you to choose a metric when you create a collection:
| Metric | Measures | Better means | Typical use |
|---|---|---|---|
| Cosine | The angle between vectors | Higher similarity (or lower cosine distance) | Text embeddings (the most common choice) |
| Dot product | Angle and length together | Higher | Models trained for it; fastest when vectors are normalised |
| Euclidean (L2) | Straight-line distance | Lower | Image features, some older models |
For normalised vectors (length 1), all three give the same ranking:
import math
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def cosine(a, b):
return dot(a, b) / (math.sqrt(dot(a, a)) * math.sqrt(dot(b, b)))
def euclidean(a, b):
return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))
def normalise(v):
length = math.sqrt(dot(v, v))
return [x / length for x in v]
query = normalise([0.6, 0.8, 0.0])
docs = {
"street food": normalise([0.7, 0.6, 0.0]),
"pasta": normalise([0.1, 0.9, 0.1]),
"laptops": normalise([0.0, 0.1, 0.9]),
}
print(f"{'document':<12} {'cosine':>7} {'dot':>7} {'distance':>9}")
for name, v in docs.items():
print(f"{name:<12} {cosine(query, v):>7.3f} {dot(query, v):>7.3f} {euclidean(query, v):>9.3f}")Cosine and dot product are identical here, and distance goes down exactly as similarity goes up (for unit vectors, distance² = 2 − 2 × cosine). Use the metric your embedding model's documentation recommends; many text models produce normalised vectors, so cosine and dot product agree.
Trading a little accuracy for a lot of speed
The program below uses one of the simplest ANN ideas. Random “planes” cut the space into buckets, and a search only looks inside the query's bucket. Using several independent sets of buckets (tables) catches neighbours that one set misses:
import heapq
import random
random.seed(7)
DIMS = 16
def random_vector():
return [random.uniform(-1, 1) for _ in range(DIMS)]
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
vectors = [random_vector() for _ in range(5000)]
queries = [random_vector() for _ in range(20)]
def exact_top(query, k=5):
return heapq.nlargest(k, range(len(vectors)), key=lambda i: dot(query, vectors[i]))
# Approximate search: random "hyperplanes" split space into buckets.
# Each vector gets a key: one bit per plane (which side of the plane it is on).
def build_buckets(n_planes, n_tables):
tables = []
for _ in range(n_tables):
planes = [random_vector() for _ in range(n_planes)]
buckets = {}
for i, v in enumerate(vectors):
key = tuple(dot(p, v) > 0 for p in planes)
buckets.setdefault(key, []).append(i)
tables.append((planes, buckets))
return tables
def approx_top(query, tables, k=5):
candidates = set()
for planes, buckets in tables:
key = tuple(dot(p, query) > 0 for p in planes)
candidates.update(buckets.get(key, [])) # only look in matching buckets
best = heapq.nlargest(k, candidates, key=lambda i: dot(query, vectors[i]))
return best, len(candidates)
for n_tables in [1, 4, 12]:
tables = build_buckets(n_planes=6, n_tables=n_tables)
found = checked = 0
for q in queries:
approx, n_checked = approx_top(q, tables)
found += len(set(approx) & set(exact_top(q)))
checked += n_checked
recall = found / (5 * len(queries))
print(f"{n_tables:>2} table{'s' if n_tables > 1 else ' '}: compared {checked // len(queries):>4} of 5000 vectors, recall@5 = {recall:.0%}")Read the trade-off from the output: checking more vectors finds more of the true neighbours. Every ANN method has a setting like this, a speed versus recall knob.
This bucket method is weak on purely random data like ours. The indexes used by real vector databases, covered in the next lesson, do far better on real embeddings: they commonly reach 95–99% recall while comparing the query with only a tiny fraction of the collection.
Common mistakes
Measure the recall of an approximate search: the share of the true nearest neighbours that it found. Order does not matter, only membership.
exact = [12, 7, 33, 90, 41] # true 5 nearest neighbours approx = [12, 33, 7, 58, 41] # what a fast approximate index returned # How many of the true neighbours did the approximate search find? # Print it as: Recall@5: 80%
An approximate search returns 8 of the true 10 nearest neighbours. What is its recall@10?
Summary
- k-NN search finds the k stored vectors most similar to a query; exact search compares with every vector.
- Common metrics are cosine, dot product and Euclidean; for normalised vectors they rank results the same way.
- ANN search compares with only a fraction of the vectors, trading a little accuracy for a lot of speed.
- Recall@k measures that accuracy: the share of the true top k that were returned.
Next: the two indexes behind most vector databases, HNSW and IVF.
Finished reading? Tick it off to track your progress.