Sub topic 3
Exact nearest neighbor search with brute force
This chapter assumes you can read basic Python and NumPy, know what a dot product is, and know roughly what an embedding is. The previous chapters covered embeddings and similarity metrics. Here you will build the simplest correct vector search and learn why every later index is judged against it.
What exact search means
Exact nearest neighbor search, also called brute force or flat search, compares the query against every stored vector. It then returns the k vectors with the best score. There is no index structure, no training step, and no approximation. If the metric and the data are fixed, the answer is the true answer.
The procedure has three steps:
- Score every stored vector against the query.
- Order the scores.
- Return the ids of the top k.
Because it is exact, it is the ground truth for measuring approximate indexes. In a later chapter you will compute recall by comparing an approximate index's answers with the answers from this method.
A complete implementation
The code below builds 1,000 random 64-dimensional vectors and one query. It normalizes everything, scores all vectors with one matrix product, and returns the five best.
import numpy as np
rng = np.random.default_rng(0)
vectors = rng.normal(size=(1000, 64)).astype("float32")
query = rng.normal(size=64).astype("float32")
def normalize(x):
return x / np.linalg.norm(x, axis=-1, keepdims=True)
# After normalization, the dot product equals cosine similarity.
scores = normalize(vectors) @ normalize(query)
top5 = np.argsort(-scores)[:5]
print(top5, scores[top5])The pieces matter:
vectorshas shape(1000, 64): one row per item.normalizedivides each vector by its length. Theaxis=-1argument works on both a matrix and a single vector, andkeepdims=Truekeeps the shape compatible for division.normalize(vectors) @ normalize(query)multiplies a(1000, 64)matrix by a(64,)vector and yields 1,000 scores in one call. NumPy hands this to an optimized linear algebra routine, which is far faster than a Python loop.np.argsort(-scores)sorts from highest to lowest by negating the scores. It returns positions, which you would map to your own item ids.
Since the data is random, the scores are small. With real embeddings, the top results would be close to 1.0 for cosine similarity.
Matching the metric to the scoring code
The code above ranks by cosine similarity. The metric you pick must match what the embedding model was trained for, as covered in the previous chapter. The table shows how to adapt the scoring step.
| Metric | Score computation | Best result is |
|---|---|---|
| Cosine similarity | Normalize both sides, then dot product | Highest |
| Dot product | `vectors @ query` with no normalization | Highest |
| Euclidean (L2) distance | Distance between query and each row | Lowest |
For Euclidean distance the sort direction flips. A common mistake is to reuse np.argsort(-scores) on distances, which returns the farthest items instead of the nearest.
import numpy as np
rng = np.random.default_rng(1)
vectors = rng.normal(size=(1000, 64)).astype("float32")
query = rng.normal(size=64).astype("float32")
# Squared L2 distance. The square root is skipped because it does not
# change the ordering.
diff = vectors - query
dist2 = np.einsum("ij,ij->i", diff, diff)
top5 = np.argsort(dist2)[:5]
print(top5, dist2[top5])Skipping the square root is safe for ranking because the square root is monotonic: if one squared distance is smaller than another, so is its root. Many libraries return squared L2 for this reason, so do not compare their numbers with unsquared distances.
Normalization and a useful identity
If both vectors have length 1, then the squared Euclidean distance equals 2 - 2 * cosine. So for normalized vectors, cosine, dot product and Euclidean distance all produce the same ranking. This is why many systems normalize embeddings once at ingestion time and then use whichever metric is fastest.
Normalize at write time when you can. Normalizing the whole corpus on every query, as the first example does for clarity, wastes work. In production you would store the normalized matrix and normalize only the query.
Getting only the top k efficiently
np.argsort sorts all 1,000 scores, which costs O(n log n). You only need the best k. A partial selection is cheaper:
import numpy as np
def top_k(scores, k):
# argpartition places the k largest scores in the last k slots, unordered.
idx = np.argpartition(-scores, k - 1)[:k]
# Sort only those k candidates.
return idx[np.argsort(-scores[idx])]
scores = np.random.default_rng(2).normal(size=100_000)
print(top_k(scores, 5))np.argpartition runs in O(n) on average. It guarantees that the first k positions hold the k best items, but not in order, so you sort just those k. For large n this is noticeably faster than a full sort.
Cost model
Let n be the number of vectors and d the dimension. Scoring one query costs about n × d multiply-add operations. Memory for float32 vectors is n × d × 4 bytes.
| Vectors (n) | Dimension (d) | Memory in float32 | Multiply-adds per query |
|---|---|---|---|
| 10,000 | 768 | about 31 MB | about 7.7 million |
| 1,000,000 | 768 | about 3.1 GB | about 768 million |
| 100,000,000 | 768 | about 307 GB | about 76.8 billion |
Per query, the work grows linearly with n. Doubling the data doubles the latency. The next chapter examines why this stops being acceptable and why geometry in high dimensions makes simple shortcuts hard.
Brute force is often memory-bandwidth bound rather than compute bound. Each stored vector is read once per query and used for few arithmetic operations, so the speed of reading memory sets the limit. Batching several queries into one matrix product reuses each loaded vector across queries and raises throughput.
import numpy as np
rng = np.random.default_rng(3)
vectors = rng.normal(size=(5000, 64)).astype("float32")
queries = rng.normal(size=(8, 64)).astype("float32")
scores = queries @ vectors.T # shape (8, 5000)
top3 = np.argsort(-scores, axis=1)[:, :3]
print(top3)Edge cases and common errors
- Zero vectors. Normalizing a vector of all zeros divides by zero and produces NaN values. Check lengths before normalizing, and decide how to treat items with no embedding.
- Ties. Duplicate vectors get identical scores. Sorting does not guarantee which one comes first, so results can differ between runs or libraries. If you need determinism, break ties by id.
- k larger than n.
argpartitionraises an error if k exceeds the number of items. Clamp k to n. - Wrong sort direction. Similarities rank high to low. Distances rank low to high.
- Mixed dtypes. Float64 doubles memory and often halves speed. Keep vectors in float32 unless you have a reason not to.
- Mismatched models. Queries and documents must come from the same embedding model. Scores between vectors from different models are meaningless, even if the dimensions match.
When brute force is the right answer
Exact search is not only a teaching tool. It is a good choice when:
- The collection is small, roughly up to a few hundred thousand vectors, depending on dimension and latency target.
- You need perfect recall and cannot accept missed results.
- Queries are rare or run in batch, so per-query latency matters little.
- A filter shrinks the candidate set so much that scoring the survivors exactly is cheap. Later chapters on metadata filtering return to this idea.
Using it first also keeps your system simple. Add an approximate index only when measurements show you need one.
Summary
Brute force scores every vector, so it is exact, simple and needs no index. Its cost grows linearly with the number of vectors and with the dimension. Match the sort direction to the metric, normalize once at write time, use partial selection for top k, and batch queries when you can. Keep the result around, because you will use it as the baseline for recall.
Exercise
You switch a search function from cosine similarity to Euclidean distance but leave the line np.argsort(-scores)[:5] unchanged. What goes wrong, and how do you fix it? Also, why can you skip the square root when ranking by Euclidean distance?
Show answer
Negating distances and sorting ascending puts the largest distances first, so the function returns the five farthest vectors instead of the nearest. Fix it by sorting ascending on the distances, np.argsort(dist)[:5]. The square root can be skipped because it is monotonic: it never changes which of two values is larger, so the ranking of squared distances matches the ranking of distances.
Exercise
A collection holds 2,000,000 vectors of dimension 384 stored as float32. Estimate the memory for the vectors and the number of multiply-adds for one brute-force query.
Show answer
Memory is 2,000,000 × 384 × 4 bytes = 3,072,000,000 bytes, about 3.1 GB. Multiply-adds are 2,000,000 × 384 = 768,000,000 per query.