vector indexes
nearest neighbours for embeddings. HNSW graphs and IVF lists, approximate on purpose.
- address
- everything.index_internals.vector_indexes
- part
- part 13, inside indexes
- chapter
- chapter 12 of 12
- reading time
- 8 min
an embedding is a vector of hundreds of numbers, and "similar" means "close". exact nearest-neighbour search has to compare the query with every row, so vector indexes give up exactness on purpose. HNSW builds a layered graph and walks it greedily toward the query; IVF clusters the vectors into lists and scans only the few lists nearest the query. both trade recall (how many of the true nearest you get back) for speed, with one knob each: hnsw.ef_search and ivfflat.probes.
the picture
you know how GiST finds the nearest points with bounding boxes? in 2 dimensions a box rules out most of the plane. in 768 dimensions it rules out almost nothing: every point is about the same distance from every box. that's the "curse of dimensionality", and it's why exact indexes stop working for embeddings. the way out is to stop insisting on the exact answer.
two everyday versions of that. finding a house in a city you don't know: you ask someone at the airport for the right district (a long jump), then someone there for the street, then knock on doors nearby (HNSW: long links on top, short ones at the bottom). or you sort the city into neighbourhoods once, and when someone asks, you only search the neighbourhood or two whose centre is closest to the address (IVF). both usually get it right, and occasionally miss a house just over a border.
layer 2start at the entry point, on the top layer (2). only a few points reach this high, so the links here are long jumps.
exact search first
pgvector adds a vector type and distance operators: <-> (euclidean), <=> (cosine distance), <#> (negative inner product). the browser's engine doesn't have it, so everything here ran on a real postgres 18.6 server. 10,000 vectors of 32 numbers, made deterministically from a hash, and 50 query vectors:
CREATE EXTENSION vector;
SELECT extversion FROM pg_extension WHERE extname = 'vector';
CREATE TABLE items AS
SELECT g AS id,
(SELECT array_agg((hashint4(g * 64 + d) % 1000) / 1000.0 ORDER BY d)
FROM generate_series(1, 32) AS d)::vector(32) AS v
FROM generate_series(1, 10000) AS g;
CREATE TABLE queries AS
SELECT q AS qid,
(SELECT array_agg((hashint4(-q * 64 - d) % 1000) / 1000.0 ORDER BY d)
FROM generate_series(1, 32) AS d)::vector(32) AS v
FROM generate_series(1, 50) AS q;
ANALYZE items;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id FROM items ORDER BY v <-> (SELECT v FROM queries WHERE qid = 1) LIMIT 10;| extversiontext |
|---|
| 0.8.6 |
checked on a real postgres 18.6 server. the browser engine can't run this one (the vector extension, which isn't in the browser engine).
no index: a seq scan computes all 10,000 distances, and a top-N heapsort keeps the 10 smallest, reading the whole table (258 buffers). that's exact, and it's the yardstick: the true 10 nearest for each of the 50 queries go in a table, and recall() measures how many of those an index finds:
CREATE TABLE truth AS
SELECT qid, (SELECT array_agg(id ORDER BY d, id)
FROM (SELECT id, i.v <-> q.v AS d FROM items AS i ORDER BY d, id LIMIT 10) AS nn) AS ids
FROM queries AS q;
-- recall@10 over the 50 queries, with one setting changed for the duration
CREATE FUNCTION recall(setting text DEFAULT NULL, val int DEFAULT NULL)
RETURNS numeric LANGUAGE plpgsql AS $$
DECLARE r record; hits int := 0; got int[];
BEGIN
IF setting IS NOT NULL THEN PERFORM set_config(setting, val::text, true); END IF;
FOR r IN SELECT t.ids, q.v FROM truth AS t JOIN queries AS q USING (qid) LOOP
SELECT array_agg(id) INTO got FROM (SELECT id FROM items ORDER BY v <-> r.v LIMIT 10) AS s;
hits := hits + (SELECT count(*) FROM unnest(r.ids) AS x WHERE x = ANY (got));
END LOOP;
RETURN round(hits / 500.0, 3);
END $$;
SELECT recall() AS exact_recall;| exact_recallnumeric |
|---|
| 1.000 |
checked on a real postgres 18.6 server. the browser engine can't run this one.
1.000 without an index, of course: the seq scan is exact.
HNSW
HNSW (hierarchical navigable small world graphs, Malkov and Yashunin, 2016) puts every vector in a graph on layer 0, a random few on layer 1, fewer on layer 2, and so on, each linked to up to m near neighbours on each of its layers (pgvector's default m is 16, 32 on layer 0). an insert searches the graph for its own neighbours, with a candidate list of ef_construction (default 64). a query starts at the top, walks greedily toward the query vector, drops a layer, and at layer 0 runs a best-first search keeping hnsw.ef_search candidates (default 40):
CREATE INDEX items_hnsw ON items USING hnsw (v vector_l2_ops);
SELECT ef AS ef_search, recall('hnsw.ef_search', ef)
FROM unnest(ARRAY[10, 20, 40, 100, 200]) AS ef
ORDER BY ef;| ef_searchint4 | recallnumeric |
|---|---|
| 10 | 0.680 |
| 20 | 0.868 |
| 40 | 0.954 |
| 100 | 0.990 |
| 200 | 0.998 |
checked on a real postgres 18.6 server. the browser engine can't run this one.
at the default of 40 the index found 0.954 of the true nearest; at 10, only 0.68. raising ef_search widens the search and buys recall back, at the cost of looking at more of the graph. none of these numbers say "wrong": the index returned the closest vectors it found, and an approximate index is allowed to miss.
here's one query at the default, with its buffer count:
SET hnsw.ef_search = 40;
EXPLAIN (ANALYZE, BUFFERS, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id FROM items ORDER BY v <-> (SELECT v FROM queries WHERE qid = 1) LIMIT 10;checked on a real postgres 18.6 server. the browser engine can't run this one.
Order By on an Index Scan, like GiST's nearest-neighbour scan, but approximate.
SELECT id FROM items ORDER BY v <-> $1 LIMIT 10;IVF
IVFFlat (an inverted file of flat, uncompressed vectors) runs k-means at build time to find lists centroids, and files each vector under its nearest one. a query compares itself with the centroids and scans only the ivfflat.probes nearest lists (default 1):
DROP INDEX items_hnsw;
CREATE INDEX items_ivf ON items USING ivfflat (v vector_l2_ops) WITH (lists = 100);
SELECT p AS probes, recall('ivfflat.probes', p)
FROM unnest(ARRAY[1, 5, 10, 20, 50]) AS p
ORDER BY p;| probesint4 | recallnumeric |
|---|---|
| 1 | 0.152 |
| 5 | 0.390 |
| 10 | 0.572 |
| 20 | 0.774 |
| 50 | 0.970 |
checked on a real postgres 18.6 server. the browser engine can't run this one.
one probe out of 100 lists found 0.152 of the true neighbours: random 32-dimensional points don't cluster, so the nearest ones are spread over many lists. it took 50 probes, half the lists, to get to 0.97. the README's starting points are lists = rows / 1000 (up to a million rows) and probes = √lists, and it notes IVFFlat must be built after the data is loaded, since the centroids come from the data. HNSW has no training step.
CREATE INDEX items_hnsw2 ON items USING hnsw (v vector_l2_ops);
SELECT relname AS rel, pg_relation_size(oid) / 8192 AS pages
FROM pg_class WHERE relname IN ('items', 'items_ivf', 'items_hnsw2')
ORDER BY pages;| relname | pagesint8 |
|---|---|
| items_ivf | 219 |
| items | 256 |
| items_hnsw2 | 532 |
checked on a real postgres 18.6 server. the browser engine can't run this one.
the sizes, on this build: IVFFlat is a little smaller than the table (it stores every vector once, plus the centroids), HNSW about twice the table, for the links.
one level deeperfilters and the missing rows
WHERE category = 'tea' ORDER BY v <-> $1 LIMIT 10 with an HNSW index: the index walks the graph and returns its ef_search best candidates, then the filter throws away the ones that aren't tea. if tea is 5% of the rows, 40 candidates leave about 2, and you get 2 rows back, not 10. pgvector 0.8 added iterative index scans (hnsw.iterative_scan), which keep walking until enough rows pass the filter. the alternatives are a partial index per category, or a bigger ef_search.
keylines
- exact nearest-neighbour search compares the query with every row; vector indexes skip most of them on purpose.
- HNSW is a layered graph: long jumps on top, a best-first search on layer 0 with ef_search candidates.
- IVF clusters vectors into lists and scans the probes nearest lists.
- recall is the price, and each index has one knob that buys it back with work: ef_search, probes.
- adding the index changes which rows come back. measure recall against an exact search on your data.