Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

What does a vector database store, and how does an approximate nearest neighbour index like HNSW answer a similarity query? When can PostgreSQL with pgvector be enough?

A vector database stores embeddings, fixed-length arrays of floats produced by a model, together with metadata, and answers queries like 'give me the k vectors closest to this one' using cosine distance, dot product or Euclidean distance. An approximate index such as HNSW builds a layered graph of neighbours and walks it from a coarse top layer down to a dense bottom layer, examining only a small fraction of the vectors at the cost of occasionally missing a true neighbour. PostgreSQL with pgvector, which supports HNSW and IVFFlat indexes, is often enough for millions of vectors and has the advantage of keeping embeddings in the same transactional database as the records they describe.

Why this question is asked

Retrieval features such as semantic search, recommendations and retrieval-augmented generation all rest on one operation: finding the stored items most similar to a query. Teams are often told they need a new database for this, and interviewers ask the question to see whether we understand what is actually being stored, why exact search does not scale, how the most common index works, and when our existing PostgreSQL is perfectly adequate. In this answer, we will recap embeddings and distance, see why exact search is slow, walk through how HNSW answers a query, try it in pgvector, and then discuss when a dedicated vector database is worth it.

1A Quick Recap of Embeddings and Similarity

An embedding is the output of a model that turns a piece of content, a paragraph, an image or a product, into a list of numbers of fixed length, for example 768 or 1,536 floats. The model is trained so that similar content produces vectors that point in similar directions. Two paragraphs about refund policy end up close together, and a paragraph about database indexes ends up far away from both.

Closeness is measured by a distance function. Cosine distance compares only the angle between two vectors, ignoring their length. Dot product, also called inner product, is the same as cosine when vectors are normalised to length 1. Euclidean distance, also called L2, is the straight-line distance between the two points. The embedding model's documentation tells us which one it was trained for, and we must use the same one at query time.

A vector database stores these vectors along with metadata such as the document id, tenant and language, and answers top-k queries: return the 10 stored vectors nearest to this query vector.

2Why Exact Search Does Not Scale

The simplest correct approach is to compare the query with every stored vector and keep the best k. That is called exact or brute-force search, and its cost is easy to estimate.

Properties
vectors = 5_000_000
dimensions = 1_536
flops_per_q = vectors * dimensions * 2 # about 15,000,000,000 per query
bytes_read = vectors * dimensions * 4 # about 30 GB of floats per query
# even at memory speed, that is seconds per query on one core

So exact search is fine for tens of thousands of vectors and becomes too slow for millions at interactive rates. Approximate nearest neighbour indexes, ANN for short, avoid looking at most of the vectors. The price is recall: the fraction of the true top-k that the index actually returns. A well-tuned index often reaches 95 to 99 percent recall while examining well under one percent of the data.

3How HNSW Answers a Similarity Query

HNSW stands for Hierarchical Navigable Small World. During indexing, each vector becomes a node in a graph and is connected to its nearest neighbours. The graph has several layers. The bottom layer contains every vector, densely connected. Each higher layer contains a random, much smaller subset of the vectors, so the top layer has only a handful of nodes with long-range links. It works like an express train, a regional train and a local bus.

A query starts at an entry point in the top layer and greedily moves to whichever neighbour is closer to the query vector, until no neighbour is closer. Then it drops to the next layer from that node and repeats. At the bottom layer it keeps a list of the best candidates seen so far, of size ef_search, and keeps exploring neighbours of those candidates until the list stops improving. Finally it returns the best k from that list.

Step throughAn HNSW search for the 10 nearest vectors
  1. Start at the entry point in the top layerfew nodes, long links
  2. Move to the closest neighbourgreedy step toward the query
  3. Is any neighbour closer?
    YesKeep moving on this layerNoDrop to the next layer down
  4. Reach the bottom layerevery vector is here
  5. Explore with a candidate list of size ef_searchdefault 40 in pgvector
  6. Return the best 10 candidatesapproximate top-k

6 steps in order. Play them, or step through them one at a time.

Three parameters control the trade-offs. M is the number of links each node keeps; more links mean better recall and more memory. ef_construction is how hard the index tries to find good neighbours while building; higher means a better graph and a slower build. ef_search is the size of the candidate list at query time; raising it improves recall and costs latency. Notice that ef_search can be changed per query without rebuilding the index, which makes it the main tuning knob.

4Trying It in PostgreSQL With pgvector

pgvector is a PostgreSQL extension that adds a vector type, distance operators and two index types, HNSW and IVFFlat. IVFFlat clusters the vectors into lists and searches only the closest lists; it builds faster and uses less memory but usually gives lower recall than HNSW for the same speed.

SQL
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE documents (
id bigserial PRIMARY KEY,
tenant_id bigint NOT NULL,
body text NOT NULL,
embedding vector(1536) NOT NULL
);
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64); -- the defaults, written out
SET hnsw.ef_search = 100; -- more candidates, better recall
SELECT id, body, embedding <=> $1 AS distance -- <=> is cosine distance
FROM documents
ORDER BY embedding <=> $1
LIMIT 10; -- 10 nearest by cosine

The operator in ORDER BY must match the operator class of the index: vector_cosine_ops goes with <=>, vector_l2_ops with <->, and vector_ip_ops with <#>, which returns the negative inner product. If they do not match, PostgreSQL cannot use the index and silently falls back to a full scan. HNSW indexes on the vector type support up to 2,000 dimensions; the halfvec type stores half-precision floats, halves memory and allows more dimensions, so check your pgvector version for the current limits.

5When pgvector Is Enough and When It Is Not

pgvector is often enough for millions of vectors, and its biggest advantage is not speed but location. The embeddings live next to the rows they describe, in the same transactions, under the same backups, the same row-level security and the same joins. When a document is deleted, its embedding is deleted in the same commit, and we never have to build a sync pipeline to another store. For a product with a few million chunks and tens or hundreds of queries per second, that simplicity usually wins.

A dedicated vector database earns its place at a different scale. When we have hundreds of millions or billions of vectors, an index that no longer fits in one machine's memory, thousands of queries per second, or heavy filtering combined with similarity, systems built for this job offer sharding, quantization to shrink vectors, filtered search built into the index, and tiering to disk. Search engines such as OpenSearch and Elasticsearch are a middle option, combining vector search with keyword search in one query. The decision should be made on measured size and load, not on the label 'AI project'.

Choosing where vectors live
SituationGood fitWhy
Under about 10 million vectors, moderate QPSPostgreSQL with pgvectorone store, transactions, existing backups and access control
Need keyword plus vector rankingSearch engine with vector supporthybrid queries in one place
Hundreds of millions of vectors or very high QPSDedicated vector databasesharding, quantization, filtered ANN built in
Under about 100,000 vectorsExact search, maybe no indexbrute force is fast enough and has perfect recall

6Follow-up questions

What is the difference between recall and precision here?

Recall measures how many of the true nearest neighbours the index returned; it is about the index's approximation. Whether those neighbours are actually relevant to the user is a separate question about the embedding model and chunking. A perfect index cannot fix a poor model.

How much memory does an HNSW index need?

Roughly the vectors themselves plus the graph links. At 1,536 float dimensions each vector is about 6 KB, so 5 million vectors are about 30 GB before links. Half-precision storage or quantization reduces that, and it is the main reason large deployments move to systems with built-in compression.

Why might HNSW build slowly?

Building inserts each vector into the graph by searching for its neighbours, so it is far more expensive than a B-tree build. In pgvector, raising maintenance_work_mem so the graph fits in memory and allowing parallel workers speed it up a lot, and building after a bulk load is faster than inserting into an existing index.

7Conclusion

In this answer, we saw that a vector database stores embeddings with metadata and returns the k nearest vectors under a distance function that must match the model. Exact search compares against every vector and does not scale to millions at interactive speed, so ANN indexes trade a little recall for a large speedup. HNSW builds a layered neighbour graph and searches from coarse to fine layers, with M, ef_construction and ef_search controlling recall, memory and speed. pgvector brings HNSW and IVFFlat into PostgreSQL and is often enough, while dedicated systems help at very large scale, high query rates and heavy filtering.

What to say in the interviewAbout 90 seconds aloud

Open with

A vector database stores embeddings, which are fixed-length float arrays a model produces for text or images, along with metadata like the document and tenant. The query is: give me the k stored vectors closest to this query vector, by cosine distance, dot product or Euclidean distance, whichever the model was trained for.

Then, if they want more

Exact search compares the query with every vector, which is perfect but too slow at millions of vectors, so we use approximate indexes that trade a little recall for speed. HNSW is the most common one.

It builds a graph where each vector links to its nearest neighbours, organised in layers: a sparse top layer with long jumps and a bottom layer with everything. A search starts at the top, greedily walks toward the query, drops a layer, and at the bottom explores a candidate list of size ef_search before returning the best k.

M controls links per node and memory, ef_construction controls build quality, and ef_search is the query-time recall knob. pgvector gives PostgreSQL HNSW and IVFFlat indexes, and for a few million vectors at moderate load it is usually enough, with the big win that embeddings sit in the same transactions and access controls as the data.

I would move to a dedicated store only at very large scale or very high query rates.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Redis documentation, MongoDB manual
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What does a vector database store, and how does an approximate nearest neighbour index...": https://scrivio-interview-library.netlify.app/databases/nosql-fundamentals/3c094d1d15/