HNSW indexes
hnsw, §M14.12 V4b, V5, V6
Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.
CREATE INDEX [name] ON t USING hnsw (col [opclass]) [PARTITION BY (c, …)] [WITH (m = 16, ef_construction = 64, quantize = 'none', rescore = n)] (PARTITION BY and quantize below) on a vector(n) column (one without dimensions
22023; another type, or more than one column, 0A000): the operator
classes are pgvector’s — vector_l2_ops (the default, <->),
vector_cosine_ops (<=>), vector_ip_ops (<#>), vector_l1_ops
(<+>) — and so are the options’ bounds (m 2–100, ef_construction
4–1000 and at least 2 · m); the record keeps both options. A NULL
vector is not indexed, nor, for vector_cosine_ops, one of zero length.
The graph is hnsw::graph (bench/ann’s core: the paper’s search and
inserts with hnswlib’s heuristic, ParlayANN’s batch inserts with
NN-descent’s local join, FreshDiskANN’s delete consolidation, a node’s
level from a hash of it); its distances keep the SQL operator’s order
(squared Euclidean; one minus the dot product over vectors stored
normalized for the cosine).
Storage (hnsw::store, PLAN.md §M14.12 V4’s model (C)): under the
index’s prefix, r the root, o + id the objects, d + primary key +
nonce a delta row (its vector), x + primary key + vector hash + nonce a
dead row. The graph is immutable objects keyed by a hash of their
contents: vector pages and adjacency pages of 64 nodes (decoded into
chunks of 4,096 in memory), patches of the lists a fold changed (in
memory a chain of levels kept short by the logarithmic method, Bentley
and Saxe: a level takes in the one before while that holds no more
patches, so a lookup walks O(log patches) levels), a directory of the
pages in parts of 256, the dead nodes;
decoded, they are shared by every snapshot (object_cache, shared with the text index: up to 1 GiB,
the least recently used dropped past it). A write puts the row’s
vector into the delta and, for a delete or an update of the vector, a
dead key, in the statement’s transaction (an update of other columns
writes nothing): every key is new, so writers never conflict. The
upkeep — each step a transaction of its own, run again on a conflict
(with another upkeep only) — seals: the delta and dead keys it sees
moved into a sealed object the root lists (an LSM’s memtable flush),
then the delta’s range vacuumed (Kv::vacuum_range: the moved keys’
tombstones, which every search’s scan of the delta would otherwise step
over — 2 µs a row growing to 20 as the seals went on, before); folds:
every sealed object’s rows the table still has as they are inserted into
the graph in batches on the machine’s threads, the nodes of the rows
updated or deleted marked dead (passed over by searches), and once the
dead are 2 % of the graph cut out (each list through a dead node
rewritten from its live neighbours’, the entry point moved off); and
compacts once a fold leaves the patches past a tenth of the graph’s
edges — apart from the folds, as an LSM compacts beside its flushes:
the pages the patches touch rewritten from a snapshot on the machine’s
threads (Index::compaction), put in transactions of about 8 MiB of
new objects each (no conflicts, none on the KV’s path for large
transactions), then swapped in between two folds in a short transaction
(Index::install: the patches it took dropped, later folds’ kept; a
graph rewritten meanwhile by a consolidation refuses it, its pages
deleted), and the new pages read into memory (Index::warm, RocksDB’s
prepopulate_block_cache for a compaction’s output) — a fold no longer
rewrites the whole adjacency (2.7 s at 1 M rows, the delta piling up
meanwhile). It runs after each statement outside a transaction block
and each block’s commit, by that session
(index_method::after_statement(kv, wrote); PostgreSQL’s GIN
fastupdate cleans its pending list so), for each index of that
database with rows waiting (the process notes the delta’s keys written
and the rows left sealed): a seal once the delta passes the seal’s size,
a fold once the sealed rows pass the fold’s — while rows come in (a row
a second or more), only by a session whose statement may have written,
so a search never waits on it. The sizes are economic order quantities
(Harris) of what the index measures as it runs — writes and searches a
second, a fold’s fixed cost (a decayed line fitted to folds’ times
against their rows), a seal’s, and what a waiting row costs a search,
sealed and in the delta (averaged from the searches’ own scans) — at
most 10,000 rows, a fold’s nudged a fifth either way in turn; as the
writes stop their rate falls and so do the sizes, so the rows left
waiting are folded by the searches that follow. hnsw::upkeep_now
runs it whatever the sizes (tests).
hnsw::search(txn, t, i, q, ask, wanted, keep) (Ask: k, ef,
ef_most, the share of the rows expected to pass, the rows to search
among): the graph searched (its dead nodes passed over) and the sealed
rows (from memory) and the delta (from the KV) scanned, the candidates
checked against the table’s rows in the snapshot — a row gone passed
over, one found twice once, one keep refuses (a filter) left out, each
ranked by its distance as the SQL operator takes it. ef counts the
candidates that pass (as a filtered HNSW search’s result list holds
only those — hnswlib’s, ACORN’s): the graph is asked for ef over the
share expected to pass, and again — sized by the share that passed among
the rows it read (a filter that goes with the vectors passes fewer near
the query than overall) — where fewer than k passed or that share is
under half the expected, up to ef_most or until the index has no more
(pgvector 0.8’s iterative scans, sized by what was seen; a row looked at
once is not read again); hnsw::nearest is it without a filter. The
candidates are read nearest first by the graph’s distance and the
search stops once k rows that pass are nearer than the next, so it
reads about k over the share passing, not ef; a row whose vector is
no longer the one found (its distance in the graph’s terms differs, to
the bit) is passed over — its vector now is in the index too, under its
own distance.
Among given rows (PLAN.md §M14.12 V5): the search is exact over
their vectors in the index, read from memory — no graph walked
(Index::candidates_among). A row’s nodes are found by a hash of its
primary key (ByRow, kept in memory per graph and grown as nodes are
added — what a fold marks dead by, too — behind a read-write lock: the
fold takes it only to mark), all the rows’ nodes first and then their
vectors in the nodes’ order (lookups that do not wait on each other,
vectors read along their chunks), on up to parallel_workers threads of
2,048 rows each; the sealed and delta rows among them come from the
scans the search makes anyway. A node of another row (two hashes met)
or of a vector the row no longer has is checked against the row as every
candidate is. A snapshot older than the map’s graph (rebuilt since) is
searched through the graph instead.
Partitioned: PARTITION BY (c, …) (PLAN.md §M14.12 V5): CREATE INDEX ix ON t USING hnsw (v) PARTITION BY (tenant_id) [WITH (…)] keeps a
graph per value of the columns — for many tenants each too large for the
exact search above, a graph of its own size each. The columns (each with
a key encoding and equality, none the vector’s) follow the vector among
the index’s columns, and the option partition_by holds their number —
so USING hnsw (v, tenant_id) WITH (partition_by = 1) is the same index,
as pg_indexes.indexdef shows it, and a column dropped or retyped takes
the index with it as any other’s. A graph’s keys are under the index’s
prefix, p and the values key-encoded (dropping the index drops them
all); each has its own upkeep, delta, seals, folds and compactions, and
its own map of rows to nodes. A row with a NULL among the values is not
indexed (no col = value finds it). A write puts a row into its values’
graph; a row whose values change gets a dead key in the old graph and a
delta row in the new — the fold of the old graph finds the row no longer
there (current reads its values too). A search goes through one graph:
the optimizer takes an index whose PARTITION BY columns the conditions
— the filter’s, or under row-level security the policy’s (a tenant’s
tenant_id = current_setting('app.tenant')::int) — each hold equal to a
value fixed for the scan (MethodRank‘s partition; EXPLAIN … in tenant_id = …), the one with most such columns where several serve;
its costs on the partition’s rows (the table’s times the equalities’
selectivity; a table not analyzed is searched, the search finding out).
Without such conditions a partitioned index is not used. The integrity
check checks each graph against the rows with its values.
A partitioned table (§M14.20): CREATE INDEX … USING hnsw on it
makes one on each partition, a graph each; ORDER BY col <op> q LIMIT k
over it searches each partition’s index for k rows (each partition its
own choice, as below) and the sort and the limit above take the nearest
— partition pruning leaving the one a condition on the key fixes.
Quantized: WITH (quantize = …, rescore = n) (PLAN.md §M14.12 V6):
the graph holds codes instead of the vectors — in memory, in its pages
and its delta — and takes its distances between them; the rows, which a
search reads anyway, give the exact distances the answer is ordered by.
quantize is none (the default), half (IEEE halves, the nearest;
magnitudes past 65504 clamped, under 2⁻¹⁴ zero: half the bytes),
int8 (a byte a component, each m + s · byte with the vector’s own
least component m and step s = range / 255, after a header of m,
s, the bytes’ sum and the norm² they stand for — so a distance is one
integer dot product and a few multiplications: graph::Codec, the
kernels dot_u8, l1_u8; a quarter of the bytes and 16) or binary (a
bit a component, set where it is above the vector’s mean; distances the
bits that differ, the kernel hamming; a thirty-second of the bytes).
The codes of the cosine class are of the vectors normalized. rescore
(1–100; only with quantize) is the rows a search reads for each it
returns — the graph asked for at least k · rescore candidates, the
rows read until that many have passed (hnsw::search‘s reads), their
distances the rows’ own; its default is the codec’s (half 1, int8 2,
binary 5: Qdrant’s and Elasticsearch’s oversampling, measured here),
and the record keeps it. The check compares a node’s code with the
row’s vector coded. Binary codes say little of a vector of few
components: they are for embeddings of hundreds and thousands.
Searches in SQL. ORDER BY col <op> q LIMIT k [OFFSET o] (the
operator or its function — l2_distance, cosine_distance,
negative_inner_product, l1_distance — either way round), over a
table with an HNSW index on col whose operator class is that
distance’s, q the same for every row (a constant, a parameter, an
enclosing row’s value — a lateral item’s left row’s, so FROM items a, LATERAL (SELECT … ORDER BY b.v <=> a.v LIMIT k) searches once per row
—, or a subquery that does not read the row: (SELECT v FROM items WHERE id = $1), “more like this”, run once for the statement as
PostgreSQL’s InitPlan; optimizer::fixed), becomes a scan through the
index’s ranking (Access::Method‘s rank, the optimizer’s ranked,
§8.17; EXPLAIN: Index Scan using ix on t (k nearest col to q)) where
it costs less than the scan it had: about
ef · (3 + 2m / 10) rows’ reads, ef the session’s hnsw.ef_search
(default 40, 1–1000, SET / RESET) over the share of the rows the
filter is estimated to pass, against the rows the scan reads; and not
where ef passes the rows over 2m, where a search costs what reading
every row does. A scan through a key range of a B-tree index the filter
chose always becomes one, the range kept (within; EXPLAIN: … among ix: col = …) — so does a scan through a text index’s condition
(WHERE body @@ q ORDER BY emb <-> v LIMIT k; among ix: body @@ …,
its matches from the index’s rows_where, @@ checked on the rows the
graph finds where they are many): its rows are searched among exactly, reading the range’s
entries and about k rows where the range’s scan reads every row in it
— unless they are more than √(rows · (22 · ef + 20 · k))
(hnsw::among_most: where reading their entries, ~70 ns each and
~35–115 ns to find each one’s vector, costs what the graph’s search
does — asked for ef over the share passing, ~3.7 µs a candidate, and
reading ~k over it, ~3.4 µs a row; 33,000 of a million for k 10 at
ef 40), or estimated to be twice that (the range not read): the graph
then, as without one. Under
row-level security the policy and the statement’s filter above its
barrier become the search’s checks, evaluated in that order on each
row it reads — the search goes on until k rows the session may see
pass, and no predicate of the statement is evaluated on a row the policy
hides. A table not analyzed has the rows the index holds
(hnsw::rows), and keeps a primary-key range its filter chose. The
executor (exec::method_rows) gives the scan’s filter, the checks and
the hash joins’ key filters to the search as keep and reads only the
columns the plan needs (the method’s rank); the sort and the limit
above stay. When fewer than k + o rows pass — the index holds fewer
(a NULL vector is not in it, and sorts last), or the filter is
narrower than the estimate and ef reached the rows over 2m — the
scan reads the B-tree range’s rows instead, or every row without one, so
the answer is the exact one’s. A descending order, the
distance not the first key, an expression of it, a query that reads the
row, or no limit: read and sorted. hnsw::status: the nodes, dead
nodes, patches, sealed rows and delta keys. The integrity check reads
the root and every object it names, checks the edges’ ends, and that
every row with an indexed vector is in the graph (live), a sealed object
or the delta with that vector. crates/sql/tests/hnsw.rs: recall
against the exact search after the build, with a delta, after folds,
marks and consolidations and a table rewrite; a snapshot from before an
upkeep; each operator class; the definitions refused; the upkeep after
commits; ORDER BY … LIMIT through the planner — the plans chosen and
not, recall against the exact search, hnsw.ef_search, a filter, an
offset, the fallback to every row, an enclosing row’s vector, writes;
the rows left waiting folded by searches; searches among a B-tree’s
range exactly the exact search’s — through rows not yet folded, changed
vectors, deletes, the upkeep, a transaction’s own writes — a range with
fewer rows than asked for, and ranges too many to search among (expected
so, or found so) through the graph at the recall unfiltered; a policy’s
rows only, a predicate that fails on hidden rows never evaluated on
them; a partitioned index — the definition checked, each value’s graph
searched where the conditions or a policy fix it, through inserts, rows
moved between values, changed vectors, deletes, the upkeep and the
column’s type changed; a partitioned table searched in each partition
or the one its key fixes; and (unit tests in store) a compaction worked out, a fold
meanwhile, swapped in — the later patch kept, the index whole and exact
— and a second one from the same graph refused, its pages gone; a search
among rows in the graph, sealed, in the delta and changed since, on one
thread and on four. bench/ann/filtered.py: filtered searches on
SIFT-1M, nucleus against pgvector (docs/benchmarks.md). crates/sql/tests/hnsw_crash.rs:
writes, rollbacks, seals and folds on the simulation, a crash at an I/O
operation (dropped unsynced writes, torn ones), reopen — the rows a
step’s, the integrity check clean, a search at a wide ef the exact
search’s (and each tag’s graph of an index PARTITION BY (tag), rows
moving between them), the upkeep going on. bench/ann/sql.py: SIFT-1M through SQL
as bench/ann/pgvector_ref.py runs pgvector (docs/benchmarks.md).