Sub topic 7
Measuring similarity and finding nearest neighbors
Retrieval in a RAG system comes down to one operation: given a query vector, find the stored vectors closest to it. This chapter covers the similarity metrics used for that, how exact nearest-neighbor search works, and what goes wrong with it in practice.
It assumes you can read basic Python, know what a vector and a dot product are, and know that an embedding model turns text into a fixed-length list of numbers. The chapter on embeddings covers how those vectors are produced. Approximate indexes that speed up this search come in the next chapter.
What "close" means for embeddings
An embedding model maps each piece of text to a point in a high-dimensional space, commonly 384 to 3072 dimensions. The model is trained so that texts with similar meaning land near each other. Retrieval relies on that property: embed the question, then look for chunks whose vectors sit near the question vector.
"Near" needs a definition. Three measures are in common use.
| Metric | Formula | Higher means | Sensitive to length |
|---|---|---|---|
| Dot product | sum of a_i * b_i | more similar | Yes |
| Cosine similarity | dot(a, b) / (norm(a) * norm(b)) | more similar | No |
| Euclidean distance | sqrt(sum of (a_i - b_i)^2) | less similar | Yes |
Dot product
The dot product multiplies matching components and adds them up. It grows when two vectors point the same way and also when either vector is long. A vector with a large magnitude can therefore outscore a better-aligned vector with a small magnitude.
Cosine similarity
Cosine similarity divides the dot product by the product of the two vector lengths. The result is the cosine of the angle between the vectors, so it ranges from -1 (opposite) through 0 (unrelated direction) to 1 (same direction). Vector length drops out, so only direction matters. This is the default choice for text embeddings, because the meaning of a text is carried by direction and length can vary for incidental reasons.
Euclidean distance
Euclidean distance is the straight-line distance between two points. Smaller is closer, which is the opposite sign convention from the other two. If you sort by distance, sort ascending.
Normalization makes the three agree
If every vector is scaled to length 1 (L2-normalized), then the ranking is identical under all three metrics. For unit vectors, the squared Euclidean distance equals 2 - 2 * cosine, and the dot product equals the cosine. Many embedding models return unit-length vectors already, and many vector databases normalize on insert when you choose cosine. This matters for speed: a dot product is cheaper than a full cosine computation, so a common setup is to normalize once at ingestion and use the dot product at query time.
Exact search by brute force
The simplest retrieval method compares the query against every stored vector and keeps the best k. This is exact nearest-neighbor search, also called flat search. The following code implements it.
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]Here is a runnable example with tiny three-dimensional vectors standing in for real embeddings. Append it to the code above.
index = [
("Refunds are issued within 14 days.", [0.9, 0.1, 0.0]),
("Our office is in Lisbon.", [0.0, 0.2, 0.9]),
("Returns require a receipt.", [0.8, 0.3, 0.1]),
]
query = [1.0, 0.2, 0.0] # pretend this embeds "How do I get my money back?"
for score, text in top_k(query, index, k=2):
print(f"{score:.3f} {text}")The two refund-related chunks score near 1.0 and the office chunk scores near 0.2, so top_k returns the two relevant passages first.
Some details of the implementation are worth noting:
- The guard
if na and nb else 0.0avoids division by zero when a vector is all zeros. - Sorting the whole list costs O(n log n). For large n, a heap (
heapq.nlargest) finds the top k in O(n log k). - Pure Python loops are slow. Real systems use NumPy or a library that performs the same arithmetic in compiled code.
The same search with NumPy
With normalized vectors stored as a matrix, the whole search is one matrix-vector product.
import numpy as np
def normalize(matrix):
norms = np.linalg.norm(matrix, axis=1, keepdims=True)
norms[norms == 0] = 1.0
return matrix / norms
def top_k_numpy(query_vec, matrix, k=3):
q = np.asarray(query_vec, dtype=float)
q = q / (np.linalg.norm(q) or 1.0)
scores = matrix @ q # one dot product per stored vector
k = min(k, len(scores))
best = np.argpartition(-scores, k - 1)[:k] # unordered top k
return best[np.argsort(-scores[best])] # ordered by score
matrix = normalize(np.array([
[0.9, 0.1, 0.0],
[0.0, 0.2, 0.9],
[0.8, 0.3, 0.1],
]))
print(top_k_numpy([1.0, 0.2, 0.0], matrix, k=2)) # row indexes, best firstargpartition avoids sorting everything, and only the k winners are then sorted.
Why brute force stops scaling
Flat search does one pass over all vectors for every query. The cost is roughly n * d multiply-adds, where n is the number of chunks and d is the dimension. Memory is n * d * 4 bytes for 32-bit floats.
| Chunks (n) | Dimension (d) | Memory (float32) | Multiply-adds per query |
|---|---|---|---|
| 10,000 | 768 | about 31 MB | about 7.7 million |
| 1,000,000 | 768 | about 3 GB | about 770 million |
| 100,000,000 | 768 | about 307 GB | about 77 billion |
Up to a few hundred thousand vectors, flat search on one machine is often fast enough, and it has a real advantage: the results are exact, with no tuning. Past that point, latency and memory push you toward an approximate index, which gives up a small amount of accuracy for large speed gains. That trade-off is the subject of the next chapter.
Gotchas
Scores are not comparable across queries or models
A cosine of 0.78 does not mean "78% relevant". The range of scores depends on the embedding model, and even within one model the typical score for a good match varies by query. Use scores to rank within a single query. If you want a cutoff ("drop anything below X"), choose X by examining real results from your own data, and recompute it when you change models.
Query and documents must share one embedding model
Vectors from different models live in different spaces, even when the dimensions match. Comparing them produces meaningless scores. When you change the embedding model, re-embed the entire corpus.
Some models expect different prefixes for queries and documents
Several embedding models are trained with asymmetric inputs, for example a "query: " prefix for questions and a "passage: " prefix for documents. Omitting the prefix still returns vectors and still runs, but retrieval is worse. Read the model card.
Ties and near-duplicates crowd the top k
If your corpus contains near-identical chunks (repeated boilerplate, overlapping windows from the chunking step), they score almost the same, and several of the k slots go to the same content. Deduplicate at ingestion, or apply a diversity step such as maximal marginal relevance, which penalizes candidates that resemble ones already chosen.
High similarity is not the same as an answer
Embeddings capture topical closeness. A chunk that says "Refunds are not available for sale items" is very close to the question "Can I get a refund on a sale item?" and also close to "Refunds are available for sale items". Similarity search cannot distinguish negation or exact numbers reliably. Later chapters on hybrid search and reranking address this.
Distances concentrate in high dimensions
In very high-dimensional spaces, the gap between the nearest and the farthest vector shrinks relative to the distances themselves. In practice this means that the scores of the top results can be tightly bunched, and small differences in score carry little information. This is one reason to retrieve more candidates than you finally need and rerank them.
Choosing k
The parameter k decides how many neighbors you return. Small k keeps the prompt short and cheap, but it risks missing the passage that holds the answer. Large k raises the chance the answer is included, but it adds noise and cost. A common pattern is to retrieve 20 to 50 candidates by similarity, then narrow to 3 to 8 after reranking or filtering. You measure the effect with recall at k, which is covered in the evaluation chapter.
Exercise
A teammate normalizes all stored vectors to unit length but forgets to normalize the query vector. They rank by dot product. Does the ranking of results for a single query still match the cosine ranking? Would the scores match?
Show answer
The ranking still matches, but the scores do not. The dot product of the query with a unit-length vector equals the query's length times the cosine, and the query length is the same constant for every stored vector, so the order is unchanged. The raw scores are scaled by the query's length, so they are not cosine values and should not be compared across different queries.
Exercise
Using the three-dimensional index from this chapter, change the query to [0.0, 0.1, 1.0]. Which passage should rank first, and why does cosine suit this comparison better than an unnormalized dot product when stored vectors have very different lengths?
Show answer
"Our office is in Lisbon." ranks first, because its vector [0.0, 0.2, 0.9] points in almost the same direction as the query. Cosine ignores vector length, so a long vector pointing in a worse direction cannot beat a short vector pointing the right way. An unnormalized dot product rewards magnitude, so a chunk with a large vector could outrank a better match.