Database / pgvector basics Interview Questions
What is cosine distance vs cosine similarity and which does pgvector return?
Cosine similarity and cosine distance are closely related but measure different things. pgvector's <=> operator returns cosine distance, not similarity. Understanding the relationship prevents confusion when interpreting results.
| Metric | Formula | Range | Interpretation |
|---|---|---|---|
| Cosine similarity | cos(theta) = (a.b) / (|a||b|) | [-1, 1] or [0, 1] for normalised | Higher = more similar (1 = identical direction) |
| Cosine distance | 1 - cosine_similarity | [0, 2] or [0, 1] for normalised | Lower = more similar (0 = identical direction) |
-- pgvector's <=> returns COSINE DISTANCE (not similarity) -- Lower value = more similar SELECT id, content, embedding <=> '[0.1,0.2,0.3]' AS cosine_distance FROM documents ORDER BY cosine_distance -- ASC: smallest distance first = most similar LIMIT 5; -- Convert to cosine SIMILARITY: SELECT id, content, 1 - (embedding <=> '[0.1,0.2,0.3]') AS cosine_similarity FROM documents ORDER BY embedding <=> '[0.1,0.2,0.3]' -- still ORDER BY distance LIMIT 5; -- For normalised vectors (most embedding models output unit vectors): -- cosine_similarity = 1 - cosine_distance -- Also: cosine_similarity ~= inner_product for unit vectors -- So for OpenAI text-embedding-3-small (outputs unit vectors): -- <=> and <#> (after negation) give equivalent rankings -- Verify a vector is normalised (magnitude = 1.0): SELECT id, |/( embedding <-> '[0,0,0]'^2 ) AS magnitude -- or more simply: SELECT id, sqrt(embedding <.> embedding) AS magnitude -- inner product of self
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...
