The metrics behind nearest-neighbour retrieval and why ANN indexes make it fast.
Skip to solutionKEEP THE
mediumAI Engineering
How does similarity search work — cosine, dot product and Euclidean?
795 views
01
Understand the problem
similaritycosineannhnsw
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Similarity search finds the vectors closest to a query vector. Cosine similarity compares direction (angle) ignoring magnitude and is the default for normalized text embeddings; dot product equals cosine when vectors are unit-normalized; Euclidean measures straight-line distance. Exact search is O(n), so vector stores
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
pgvector: metric operators and an HNSW index
-- cosine distance operator: <=> (dot: <#>, euclidean: <->)
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
SELECT id, title, 1 - (embedding <=> $1) AS similarity
FROM chunks
WHERE tenant_id = $2 -- filter + ANN together
ORDER BY embedding <=> $1
LIMIT 10;05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 29 of 80 decoded in the AI Engineering track. One more won't hurt.