Sub topic 7
Measuring similarity and finding nearest neighbors
This chapter assumes you know basic Python, vectors, and the dot product, and that you have seen how text becomes an embedding. Here you will learn how to compare a query embedding with stored chunk embeddings and pick the closest ones.
Why similarity matters
After ingestion, each chunk has a vector. At query time, the question is embedded with the same model. Retrieval then asks: which stored vectors point in a direction most like the query vector? That question needs a number that says "how close", and a way to search with it.
Common similarity metrics
| Metric | Formula idea | Higher means |
|---|---|---|
| Dot product | sum of x·y | more similar |
| Cosine similarity | dot product divided by the product of the vector lengths | more similar |
| Euclidean distance | straight-line distance | less similar |
Cosine similarity ignores vector length and compares only direction. Its value ranges from -1 to 1. Many embedding models return unit-length vectors. For those, the dot product equals cosine similarity, and Euclidean distance ranks results in the same order. Check your model's documentation, and use the metric it was trained for.
Exact nearest-neighbor search
The simplest search is brute force. Score every stored vector against the query, sort, and keep the best k. This is exact nearest-neighbor search.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
def top_k(query_vec, index, k=3):
# index is a list of (text, vector) pairs
scored = [(cosine(query_vec, vec), text) for text, vec in index]
scored.sort(key=lambda pair: pair[0], reverse=True)
return scored[:k]The if na and nb else 0.0 guard avoids dividing by zero for an all-zero vector. Try it with tiny vectors:
index = [
("cats purr", [1.0, 0.1]),
("dogs bark", [0.2, 1.0]),
("kittens meow", [0.9, 0.2]),
]
print(top_k([1.0, 0.0], index, k=2))The two cat-related entries rank first because their vectors point closest to [1.0, 0.0].
Cost and limits
Brute force does one comparison per stored vector for every query. With a few thousand chunks this is fast. With millions of chunks and vectors of 768 or more dimensions, latency grows in step with the corpus. The next chapter covers approximate indexes, which skip most comparisons in exchange for occasionally missing a true neighbor. The exact search above remains useful as a baseline to measure how much an approximate index loses.
Common errors
- Mixing models. Query and chunks must be embedded by the same model. Vectors from different models live in unrelated spaces.
- Sorting the wrong way. Similarity is sorted high to low. Distance is sorted low to high.
- Treating nearest as relevant. The top result is only the closest one. If nothing relevant exists, you still get k results, so consider a minimum score or let later stages decide.
Exercise
A model returns unit-length vectors. Which of cosine similarity and the dot product gives the better ranking, and why?
Show answer
Neither. For unit-length vectors the dot product equals cosine similarity because both vector lengths are 1, so the rankings are identical. The dot product is cheaper because it skips the length calculation.
Exercise
Your brute-force search returns three results for a question that has no relevant chunk in the corpus. Why, and what can you add?
Show answer
Top-k search always returns the k nearest vectors, however far away they are. Add a minimum similarity threshold, tuned on your own data, or have a later step judge relevance.