Sub topic 6
The distance operators: `<->`, `<=>`, `<#>`, and `<+>`
This chapter assumes that you know basic SQL, including SELECT, ORDER BY, and LIMIT. You should also understand that an embedding is a numeric vector representing text, an image, or another object.
A distance operator compares two vectors. A smaller distance means that the vectors are more alike. pgvector provides four main operators:
| Operator | Metric | Meaning |
|---|---|---|
| `<->` | L2 distance | Straight-line distance between vectors |
| `<=>` | Cosine distance | Difference in direction between vectors |
| `<#>` | Negative inner product | Negative dot product, useful for maximum inner product search |
| `<+>` | L1 distance | Sum of absolute differences between coordinates |
Choosing a metric
The correct metric depends on how the embedding model represents similarity.
L2 distance measures the geometric distance between two points. It considers both direction and magnitude. Use it when the model's documentation recommends Euclidean distance.
Cosine distance measures the angle between vectors. It ignores their magnitude. This is a common choice for text embeddings:
SELECT id,
content,
embedding <=> '[3,1,2]' AS cosine_distance,
1 - (embedding <=> '[3,1,2]') AS cosine_similarity
FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;The <=> operator returns cosine distance, not cosine similarity. Subtracting the distance from 1 produces cosine similarity for ordinary normalized vectors. Order by the distance expression so PostgreSQL can use a cosine vector index.
The <#> operator returns the negative inner product. pgvector uses the negative value because PostgreSQL indexes and sorts in ascending order. If you need the actual inner product, negate the result:
SELECT id,
content,
-(embedding <#> '[3,1,2]') AS inner_product
FROM items
ORDER BY embedding <#> '[3,1,2]'
LIMIT 5;The <+> operator calculates L1 distance, also called Manhattan distance. It adds the absolute difference for every coordinate:
SELECT id, content, embedding <+> '[3,1,2]' AS l1_distance
FROM items
ORDER BY embedding <+> '[3,1,2]'
LIMIT 5;How ordering changes the result
Each metric can rank the same rows differently. A vector with a similar direction but a very different magnitude may rank well with cosine distance but poorly with L2 distance. Conversely, L2 gives magnitude differences full weight.
For example, if a model was trained for cosine similarity, use <=>. If its vectors are normalized to unit length, cosine and inner-product rankings are closely related. Do not assume that relationship for unnormalized vectors.
Exercise
Which expression should you use to return the five nearest rows by cosine similarity?
Show answer
Use ORDER BY embedding <=> '[3,1,2]' LIMIT 5. The operator returns cosine distance, so ascending order returns the most similar vectors.