Sub topic 2
Measuring similarity: cosine, dot product and Euclidean distance
Prerequisites and scope
This chapter assumes you know what an embedding is (a list of numbers that represents a piece of data), can read basic Python and NumPy, and remember the dot product from introductory linear algebra. It covers the three metrics that almost every vector database offers, how they relate, and how to pick one. Search algorithms come in later chapters.
An embedding model places items in a space. The metric is the rule that turns two points in that space into a single number saying how alike they are. The choice matters because the same stored vectors can give different neighbors under different metrics.
The three metrics
Let a and b be two vectors of the same length d.
Euclidean distance (L2)
Euclidean distance is the straight-line distance between the two points:
L2(a, b) = sqrt(sum_i (a_i - b_i)^2)
Smaller is more similar. It is sensitive to both direction and length (magnitude) of the vectors. Many libraries return the squared distance and skip the square root, because the ordering of results is the same and the computation is cheaper. FAISS IndexFlatL2 does this.
Dot product (inner product)
The dot product multiplies matching components and sums them:
dot(a, b) = sum_i a_i * b_i
Larger is more similar. It grows with the length of both vectors, so a long vector can outscore a closer-pointing short one. Because "larger is better" is the reverse of a distance, databases that only minimize distances store the negative inner product. pgvector's <#> operator, for example, returns the negative inner product, so ascending order puts the best match first.
Cosine similarity
Cosine similarity is the cosine of the angle between the vectors. It divides the dot product by both lengths:
cos(a, b) = dot(a, b) / (|a| * |b|)
The value lies between -1 (opposite directions) and 1 (same direction). It ignores length entirely. Cosine distance is usually defined as 1 - cos(a, b), so smaller is more similar. This is what pgvector's <=> operator returns.
| Metric | Better when | Range | Uses length? | Typical operator or setting |
|---|---|---|---|---|
| Euclidean (L2) | smaller | 0 to infinity | yes | `<->` in pgvector, `IndexFlatL2` in FAISS |
| Dot product | larger | unbounded | yes | `<#>` (negated) in pgvector, `IndexFlatIP` in FAISS |
| Cosine similarity | larger | -1 to 1 | no | `<=>` returns `1 - cos` in pgvector |
How the metrics relate
The three are not independent. Consider unit vectors, meaning vectors whose length is 1. For them:
cos(a, b) = dot(a, b), because both lengths are 1.L2(a, b)^2 = |a|^2 + |b|^2 - 2 * dot(a, b) = 2 - 2 * dot(a, b).
So for normalized vectors, ranking by cosine, by dot product, and by Euclidean distance gives the same order. Only the scale of the numbers differs. Normalizing once at write time and then using the cheapest metric (dot product) is a common, sound design.
The metrics differ when vectors are not normalized. The diagram shows how the decision follows from what your model produces.
Computing all three
The following script shows the metrics on a small example and confirms that normalization makes their rankings agree.
import numpy as np
a = np.array([1.0, 2.0, 3.0])
b = np.array([2.0, 4.0, 6.0]) # same direction as a, twice as long
c = np.array([3.0, 2.0, 1.0]) # different direction
def l2(x, y):
return np.linalg.norm(x - y)
def dot(x, y):
return float(x @ y)
def cosine(x, y):
return float(x @ y / (np.linalg.norm(x) * np.linalg.norm(y)))
for name, other in [("b", b), ("c", c)]:
print(f"a vs {name}: L2={l2(a, other):.3f} "
f"dot={dot(a, other):.1f} cos={cosine(a, other):.3f}")
# Rankings on normalized vectors agree across all three metrics.
rng = np.random.default_rng(0)
vectors = rng.normal(size=(500, 16))
query = rng.normal(size=16)
unit = lambda x: x / np.linalg.norm(x, axis=-1, keepdims=True)
v, q = unit(vectors), unit(query)
by_cos = np.argsort(-(v @ q))[:10]
by_dot = np.argsort(-(v @ q))[:10]
by_l2 = np.argsort(np.linalg.norm(v - q, axis=1))[:10]
print("cosine == L2 ranking:", np.array_equal(by_cos, by_l2))
print("cosine == dot ranking:", np.array_equal(by_cos, by_dot))For the first part, b points exactly where a points, so its cosine similarity is 1.0. Yet L2(a, b) is about 3.742, larger than L2(a, c) of about 2.828. Euclidean distance calls c the closer neighbor, while cosine calls b the closer one. The dot product favors b as well (28 against 10), but only because b is long.
This is the core difference. Cosine asks "do these point the same way?" Euclidean asks "are these at the same place?"
Choosing a metric
Follow the model
The most reliable rule is to use the metric the embedding model was trained with. A model trained with a cosine objective arranges meaning along directions, and a different metric can degrade results. Model cards and API documentation usually state the metric. Many text embedding models return normalized vectors, in which case the three choices are equivalent in ranking.
When length carries information
Some systems, especially recommenders trained with matrix factorization, encode popularity or confidence in vector length. Maximum inner product search (MIPS) is the name for finding the largest dot products. If you cosine-normalize those vectors, you discard that signal. If you use dot product on them, popular items tend to win, which may be exactly what you want or a bias you need to correct.
When length is noise
For text, the length of an embedding often reflects incidental things such as document length or token frequency. Cosine similarity removes that effect. This is why it is the default for many text retrieval setups.
Gotchas
- Mismatched metric and index. An index is built for one metric. In pgvector, the operator class (
vector_cosine_ops,vector_l2_ops,vector_ip_ops) must match the operator in your query, or the planner will not use the index and the query falls back to a slow sequential scan. - Distance versus similarity. Sorting a similarity ascending returns the worst matches. Check whether the API returns a distance (smaller is better) or a score (larger is better). Thresholds also flip direction.
- Zero vectors. Cosine divides by the length, so a zero vector gives a division by zero. Most databases return
NaNor reject the row. Filter such vectors out at ingestion. - Normalizing only one side. If you store normalized vectors but send an unnormalized query, cosine and dot product still rank the same (the query length scales every score equally), but raw scores are no longer in the -1 to 1 range and any fixed threshold breaks. Normalize both sides, or use cosine directly.
- Precision. With
float32, normalized vectors can have length like 0.99999994. This is harmless for ranking, but do not test for equality with 1.0. - Mixing models. Vectors from two different embedding models live in different spaces. No metric makes them comparable, even when the dimensions match.
Metric choice and later chapters
Approximate indexes such as HNSW and IVF, covered in later chapters, are built around a chosen metric. Their graph edges and cluster centers depend on it. Some compression methods also behave differently under inner product than under L2. Picking the metric correctly now avoids rebuilding later.
Exercises
Exercise
Vectors x = [3, 4] and y = [6, 8] are compared. Compute the cosine similarity, the Euclidean distance, and the dot product. Which metric says the vectors are "identical" and which says they are "different"?
Show answer
Cosine similarity is (36 + 48) / (5 * 10) = 50 / 50 = 1.0. Euclidean distance is sqrt(3^2 + 4^2) = 5. The dot product is 50. Cosine says the vectors are identical in direction. Euclidean distance (5, not 0) says they are different points, because y is twice as long as x.
Exercise
Your embedding model returns unit-length vectors. A colleague proposes switching a production index from cosine to Euclidean distance "for speed". What happens to the ranking of results, and what would you change in the stored thresholds?
Show answer
The ranking is unchanged, because for unit vectors L2 squared equals 2 - 2cos. Fixed thresholds must be converted: a cosine similarity cutoff of 0.8 corresponds to a squared L2 cutoff of 2 - 20.8 = 0.4 (L2 of about 0.632). The index must also be rebuilt with the matching operator class.
Exercise
A pgvector index was created with vector_cosine_ops, but the query orders by embedding <-> :q. What is the likely result and how do you fix it?
Show answer
The <-> operator is Euclidean distance, which the cosine index does not support, so the planner ignores the index and performs a sequential scan. Fix it by ordering with <=>, or by creating an index with vector_l2_ops if L2 is the intended metric.