skip to content

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.

index =
query =
ef =

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.

step 1/7
the query, the current pointlinks on this layer, points looked atreturneda true neighbour missed
model of an HNSW graph: 70 points, 3 links per point per layer, layers from a seeded draw
both ideas on 70 points in 2 dimensions. HNSW: step from the top layer down; each layer has fewer points and longer links, and the search only ever moves to a closer point. IVF: the query is compared with the centroids, and only the nearest lists are scanned. try a small ef or one probe to see a true neighbour missed.

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:

sqlempty db · session vec
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;
output, from a real postgres 18.6 server
#1 · CREATE EXTENSION
#2 · SELECT 1
extversiontext
0.8.6
(1 row)
#3 · SELECT 10000
#4 · SELECT 50
#5 · ANALYZE
#6 · EXPLAIN
Limit (actual rows=10.00 loops=1) Buffers: shared hit=261 InitPlan 1 -> Seq Scan on queries (actual rows=1.00 loops=1) Filter: (qid = 1) Rows Removed by Filter: 49 Buffers: shared hit=2 -> Sort (actual rows=10.00 loops=1) Sort Key: ((items.v <-> (InitPlan 1).col1)) Sort Method: top-N heapsort Memory: 25kB Buffers: shared hit=261 -> Seq Scan on items (actual rows=10000.00 loops=1) Buffers: shared hit=258 Planning: Buffers: shared hit=29

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:

sqlempty db · session vec
continues session vec (1 earlier block run first)
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;
output, from a real postgres 18.6 server
#1 · SELECT 50
#2 · CREATE FUNCTION
#3 · SELECT 1
exact_recallnumeric
1.000
(1 row)

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):

sqlempty db · session vec
continues session vec (2 earlier blocks run first)
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;
output, from a real postgres 18.6 server
#1 · CREATE INDEX
#2 · SELECT 5
ef_searchint4recallnumeric
100.680
200.868
400.954
1000.990
2000.998
(5 rows)

checked on a real postgres 18.6 server. the browser engine can't run this one.

ef_search 100.68 recall
ef_search 200.868 recall
ef_search 400.954 recall
ef_search 1000.99 recall
ef_search 2000.998 recall
recorded: postgres 18.6 with pgvector 0.8.6, a native server, one build
recall@10 over 50 queries by hnsw.ef_search, from the run block above. one build: the graph's layers are drawn at random, so another build lands a point or two away.

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:

sqlempty db · session vec
continues session vec (3 earlier blocks run first)
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;
output, from a real postgres 18.6 server
#1 · SET
#2 · EXPLAIN
Limit (actual rows=10.00 loops=1) Buffers: shared hit=1091 InitPlan 1 -> Seq Scan on queries (actual rows=1.00 loops=1) Filter: (qid = 1) Rows Removed by Filter: 49 Buffers: shared hit=2 -> Index Scan using items_hnsw on items (actual rows=10.00 loops=1) Order By: (v <-> (InitPlan 1).col1) Index Searches: 1 Buffers: shared hit=1091 Planning: Buffers: shared hit=1

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.

predict the output
the same 10-nearest query, before and after adding an HNSW index. what can change?
sql
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):

sqlempty db · session vec
continues session vec (4 earlier blocks run first)
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;
output, from a real postgres 18.6 server
#1 · DROP INDEX
#2 · CREATE INDEX
#3 · SELECT 5
probesint4recallnumeric
10.152
50.390
100.572
200.774
500.970
(5 rows)

checked on a real postgres 18.6 server. the browser engine can't run this one.

probes 10.152 recall
probes 50.39 recall
probes 100.572 recall
probes 200.774 recall
probes 500.97 recall
recorded: postgres 18.6 with pgvector 0.8.6, a native server, one build
recall@10 by ivfflat.probes, 100 lists, from the run block above. one build: k-means starts from random centroids.

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.

sqlempty db · session vec
continues session vec (5 earlier blocks run first)
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;
output, from a real postgres 18.6 server
#1 · CREATE INDEX
#2 · SELECT 3
relnamepagesint8
items_ivf219
items256
items_hnsw2532
(3 rows)

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.