Database / pgvector basics Interview Questions
How do you implement semantic search with pgvector and a similarity threshold?
Returning only results above a minimum similarity threshold prevents surfacing irrelevant results when no truly similar documents exist. This is preferable to always returning the top-k regardless of quality.
-- Return results only within a distance threshold -- (distance < threshold means similar enough) -- Cosine distance threshold (0 = identical, 1 = orthogonal) SELECT id, content, 1 - (embedding <=> '[...]') AS similarity, embedding <=> '[...]' AS distance FROM documents WHERE embedding <=> '[...]' < 0.3 -- only results within distance 0.3 ORDER BY distance LIMIT 20; -- L2 distance threshold (depends on your vector magnitude): SELECT id, content, embedding <-> '[...]' AS distance FROM documents WHERE embedding <-> '[...]' < 1.5 -- only close vectors ORDER BY distance LIMIT 10; -- Dynamic threshold: always return at least 1 result, -- but enforce threshold if more than 1 exists WITH ranked AS ( SELECT id, content, embedding <=> '[...]' AS dist, ROW_NUMBER() OVER (ORDER BY embedding <=> '[...]') AS rn FROM documents ) SELECT id, content, dist FROM ranked WHERE dist < 0.3 OR rn = 1 -- always return top result ORDER BY dist LIMIT 10; -- Typical cosine distance thresholds (vary by model and use case): -- 0.0 - 0.15: very similar (nearly duplicate content) -- 0.15 - 0.30: similar (same topic, different wording) -- 0.30 - 0.50: somewhat related -- > 0.50: likely unrelated (for most text embedding models)
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...
