Sub topic 2
Choosing a distance metric: L2, cosine, and inner product
This chapter assumes you can write basic SQL and have a rough idea of what an embedding is: a list of numbers that places a piece of text or an image in a space where similar items sit close together. You don't need the index chapters yet. The metric you choose here decides which index operator class you will need later.
Why the metric matters
A nearest-neighbor query needs a definition of "near". Different definitions can rank the same rows differently. The choice also has to match the model that produced your embeddings. A metric the model was not trained for can return plausible-looking but worse results.
pgvector supports three main metrics for the vector type:
| Metric | What it measures | pgvector operator | Value returned |
|---|---|---|---|
| L2 (Euclidean) | Straight-line distance between two points | `<->` | Distance, 0 or more |
| Cosine | Angle between two vectors, ignoring length | `<=>` | Cosine distance, 0 to 2 |
| Inner product | Dot product of two vectors | `<#>` | The negative of the inner product |
pgvector also has an L1 (taxicab) operator, <+>. It is rarely the first choice for embeddings, so this chapter does not cover it. The next chapters cover the operators in detail. Here they serve only as the way to compute each metric.
The three metrics
L2 distance
L2 distance is the length of the straight line between two points. For vectors a and b it is the square root of the sum of (a_i - b_i)^2. It responds to both direction and length. Two vectors pointing the same way can be far apart in L2 if one is much longer.
Cosine distance
Cosine similarity is the cosine of the angle between two vectors. It is 1 when they point the same way, 0 when they are at right angles, and -1 when they point opposite ways. Cosine distance is 1 - cosine similarity, so smaller is closer and the range is 0 to 2. Length has no effect. The vectors [1,1] and [100,100] have cosine distance 0.
Inner product
The inner product (dot product) multiplies matching components and sums them. A larger value means more similar, and it depends on both angle and length. PostgreSQL index scans return rows in ascending order, so pgvector's <#> returns the negative inner product. Ordering by <#> ascending therefore puts the largest inner products first. To display the true inner product, multiply the result by -1.
Seeing the difference on small data
This example uses 2-dimensional vectors so you can check the arithmetic by hand. The query vector is [1,1].
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE metric_demo (
name text PRIMARY KEY,
v vector(2) NOT NULL
);
INSERT INTO metric_demo (name, v) VALUES
('x', '[3,3]'),
('y', '[1,0]'),
('z', '[1.5,1]');
SELECT name,
v <-> '[1,1]' AS l2_distance,
v <=> '[1,1]' AS cosine_distance,
(v <#> '[1,1]') * -1 AS inner_product
FROM metric_demo
ORDER BY name;The values are approximately these:
| name | l2_distance | cosine_distance | inner_product |
|---|---|---|---|
| x | 2.828 | 0 | 6 |
| y | 1 | 0.293 | 1 |
| z | 0.5 | 0.019 | 2.5 |
Row x points exactly the same way as the query but is long. Cosine ranks it first, with distance 0 (the stored value may show a tiny floating-point error). L2 ranks it last. Row z is closest in absolute position, so L2 ranks it first. Inner product rewards both alignment and length, so it also puts x first here.
Which ranking is right depends on what the numbers mean. If vector length carries no meaning, as in many text-embedding models, cosine is the safer choice. If length does carry meaning, for example as a popularity or confidence signal in a recommendation model, inner product or L2 may be intended.
Normalization makes the metrics agree
A vector is normalized when its length (its L2 norm) is exactly 1. For two normalized vectors the three metrics produce the same ordering:
- The inner product equals the cosine similarity.
- The squared L2 distance equals
2 - 2 * cosine similarity.
Because of this, many embedding providers return normalized vectors. For those you can pick whichever metric is cheapest. Inner product is the cheapest to compute, since it needs no square root and no division by the vector lengths.
pgvector can show a vector's length and normalize it. l2_normalize is available in pgvector 0.7.0 and later.
SELECT vector_norm('[3,4]') AS norm,
l2_normalize('[3,4]') AS unit_vector;This returns a norm of 5 and the unit vector [0.6,0.8].
Check what your model produces before relying on this. A quick test is to select vector_norm(embedding) for a sample of rows. If the values are all about 1, the vectors are normalized.
SELECT min(vector_norm(embedding)) AS min_norm,
max(vector_norm(embedding)) AS max_norm
FROM items;The items table here is the one from the setup chapters, with an embedding vector(3) column.
Choosing a metric
Start from the model's documentation. Use the metric the model was trained with.
A few practical rules follow:
- Text embeddings from common providers are usually compared with cosine similarity. If they are normalized, inner product returns the same order and is slightly faster.
- Use L2 when the model was trained on Euclidean distance, or when the absolute position in space matters, as it can for some image and feature vectors.
- Use inner product when the model was trained with a dot-product objective, which is common in recommender systems.
- Pick one metric per column and use it everywhere. An index can serve only one operator class, so switching operators in queries means the index no longer applies.
Edge cases
Zero vectors
A zero vector has no direction. Cosine distance against it is undefined, and pgvector returns NaN. Filter such rows out before insert, or guard against them in the application.
Reading values
Cosine distance of 0.2 does not mean "80% similar" in any universal sense. The values depend on the model. Compare scores within one model and one dataset. Do not carry thresholds from one model to another.
Converting for display
Convert only for presentation. Keep ORDER BY on the raw distance expression so that an index can be used later. Sort by the distance operator, not by the converted value.
SELECT name,
1 - (v <=> '[1,1]') AS cosine_similarity
FROM metric_demo
ORDER BY v <=> '[1,1]'
LIMIT 3;Exercises
Exercise
In the demo table, which of x, y, and z is the nearest neighbor of [1,1] under L2 distance, and which under cosine distance? Why do they differ?
Show answer
Under L2 it is z (distance 0.5). Under cosine it is x (distance 0). Row x = [3,3] points in exactly the same direction as the query, so its angle is 0, but it is far away in space because it is long. L2 counts that length difference and cosine ignores it.
Exercise
You search a table of normalized embeddings with ORDER BY embedding <#> '[...]'. The first result shows -0.93. What is the inner product, and what does it equal in cosine similarity?
Show answer
The inner product is 0.93, because <#> returns the negative inner product. Since the vectors are normalized, the cosine similarity is also 0.93 (cosine distance 0.07).