Database / pgvector basics Interview Questions
What is the difference between L1 and L2 distance in pgvector?
pgvector supports both L1 (Manhattan) distance and L2 (Euclidean) distance. They measure different things and have different properties that make each better suited for certain data types.
| Property | L1 (Manhattan) <+> | L2 (Euclidean) <-> |
|---|---|---|
| Formula | sum(|a_i - b_i|) | sqrt(sum((a_i - b_i)^2)) |
| Visual metaphor | City block distance (grid navigation) | Straight-line distance |
| Sensitivity to outliers | Less sensitive (linear) | More sensitive (squares differences) |
| High-dimensional behaviour | More robust in high dimensions | Curse of dimensionality is stronger |
| Typical use | Sparse vectors; robust comparisons | General purpose; most common default |
| pgvector operator | <+> | <-> |
| Index operator class | vector_l1_ops | vector_l2_ops |
-- L2 distance (most common): SELECT id, embedding <-> '[1,2,3]' AS l2_dist FROM items ORDER BY l2_dist LIMIT 5; -- L1 (Manhattan) distance: SELECT id, embedding <+> '[1,2,3]' AS l1_dist FROM items ORDER BY l1_dist LIMIT 5; -- Comparison on same data: SELECT id, embedding <-> '[1,2,3]' AS l2_distance, embedding <+> '[1,2,3]' AS l1_distance, embedding <=> '[1,2,3]' AS cosine_distance FROM items ORDER BY l2_distance LIMIT 10; -- L1 index: CREATE INDEX ON items USING hnsw (embedding vector_l1_ops); -- Quick rule of thumb: -- Text embeddings: cosine distance <=> (magnitude-independent) -- General purpose: L2 <-> -- Sparse or outlier-prone data: L1 <+>
More Related questions...