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 <+>
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
