Database / pgvector basics Interview Questions
How do you perform a basic nearest-neighbour search with pgvector?
The fundamental pgvector query pattern combines a distance operator in the ORDER BY clause with LIMIT to retrieve the k nearest neighbours to a query vector. Without an index, this performs an exact sequential scan of all rows.
-- K-Nearest Neighbour (KNN) query: find 5 most similar documents -- Replace '[...]' with the actual query embedding from your ML model SELECT id, content, embedding <-> '[0.1,0.2,0.3]' AS distance FROM documents ORDER BY distance -- ORDER BY the distance expression LIMIT 5; -- return only the top-5 nearest -- Using cosine distance (common for text embeddings): SELECT id, content, 1 - (embedding <=> '[0.1,0.2,0.3]') AS similarity FROM documents ORDER BY embedding <=> '[0.1,0.2,0.3]' LIMIT 10; -- Self-similarity: find items similar to a known row (not itself) SELECT b.id, b.content, a.embedding <-> b.embedding AS distance FROM documents a CROSS JOIN documents b WHERE a.id = 42 AND b.id != 42 ORDER BY distance LIMIT 5; -- Or using a subquery: SELECT id, content, embedding <-> (SELECT embedding FROM documents WHERE id = 42) AS distance FROM documents WHERE id != 42 ORDER BY distance LIMIT 5; -- With a parameter placeholder (Python + psycopg2): -- cur.execute( -- 'SELECT id, content, embedding <-> %s AS dist FROM documents ORDER BY dist LIMIT 5', -- (query_embedding,) -- )
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...
