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,) -- )
More Related questions...