Vector databases and ANN indexes
What is a vector database, and how do approximate nearest neighbor (ANN) indexes like HNSW work?
TL;DR
A vector database stores embeddings and answers "find the k vectors most similar to this one" quickly, usually together with metadata filters (tenant, date, language). Comparing the query against every vector (exact search) is O(n) and too slow at millions of vectors, so these databases use approximate nearest neighbor (ANN) indexes that trade a little recall for a lot of speed. The most common is HNSW (Hierarchical Navigable Small World): a layered graph where search starts at a sparse top layer, greedily hops toward the query, and refines in denser layers below. Another family is IVF, which clusters vectors and searches only the nearest clusters.
Key points
- Options: pgvector (PostgreSQL extension; great when you already run Postgres and have up to millions of vectors), dedicated databases (Pinecone, Qdrant, Weaviate, Milvus), and search engines with vector support (Elasticsearch, OpenSearch).
- HNSW tuning:
M(links per node) andef_constructionaffect build time and quality;ef_searchtrades query speed for recall at query time. - HNSW is memory-hungry. Quantization (storing vectors as int8 or binary) cuts memory with a small quality loss.
- Filtering is tricky: filtering after the ANN search can return too few results. Prefer engines that filter during the search.
- For multi-tenant data, always filter by tenant (or use separate namespaces) so users never retrieve others' documents.
- Measure recall@k of the ANN index against exact search on a sample.
Example
CREATE EXTENSION vector;
CREATE TABLE chunks (id bigserial PRIMARY KEY, tenant_id int, content text, embedding vector(1536));
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
SELECT id, content
FROM chunks
WHERE tenant_id = 42
ORDER BY embedding <=> $1 -- cosine distance
LIMIT 5;Common follow-ups
- Do you need a dedicated vector database? Often not. pgvector keeps vectors next to your relational data and transactions. Go dedicated for very large scale or advanced features.
- How do you update documents? Re-embed changed chunks and upsert by a stable ID; delete stale chunks so they don't keep being retrieved.
What interviewers look for
Tip
Why exact search doesn't scale, how HNSW works at a high level, the recall-vs-speed trade-off, and filtering for tenants.
- Red flag: choosing a vector database before checking whether pgvector is enough.