HNSW From the Ground Up: How Vector Search Actually Finds Your Nearest Neighbor

Every RAG pipeline, semantic search feature, and recommendation feed eventually hits the same wall: a few million embedding vectors, a query vector, and a need for the k nearest neighbors — right now. Comparing the query against every stored vector — exact, brute-force search — gives perfect answers. It is also a full scan of your dataset: at a million vectors of 768 dimensions, hundreds of millions of floating-point operations per query, plus the memory traffic to read every vector.

Approximate nearest neighbor (ANN) indexes exist to break this trade: give up a little recall, gain orders of magnitude in speed. Among the many ANN algorithms, one has become the default in pgvector, Qdrant, Weaviate, Milvus, Elasticsearch, and Faiss: HNSW, Hierarchical Navigable Small World. Its behavior surprises people — one knob trades latency for accuracy, a single setting caps how many rows you can ever return, and builds stall if memory is short — so it is worth understanding how the structure works.

Why exact search breaks down in high dimensions

A k-d tree or another sorted structure answers low-dimensional nearest-neighbor queries in logarithmic time — no linear scan. Those structures rely on a simple fact — if one region of space is clearly farther than another, you can skip it. Above roughly 20–30 dimensions that reasoning collapses: distances concentrate, the gap between nearest and farthest vector shrinks relative to the distances themselves, and tree-style pruning has nothing left to skip. This is the curse of dimensionality, and it is why vector databases do not attempt exact answers at scale.

The accepted compromise is approximate search, measured by recall: of the true top-k neighbors, what fraction did the index return? Recall 0.95 means missing 5% of the true answers — usually the marginal ones, which semantic search rarely notices. Pushing recall higher costs latency and memory, so tuning is really about deciding how much of each you can afford.

Greedy routing on a proximity graph

Strip away the hierarchy for a moment and look at the base structure: a graph where each vector is a node and edges connect vectors that are close together. Search is dead simple: start at a fixed entry point, look at its neighbors, compute the distance from the query to each, and move to the closest one. Repeat. When none of the current node’s neighbors is closer than the node itself, you have hit a local minimum — stop.

This greedy walk visits a handful of nodes instead of the whole dataset — that is where the speed comes from. Proximity graphs built with a mix of short-range and long-range edges have small-world structure, so any node is reachable in a polylogarithmic number of hops. The risk is landing in a local minimum nowhere near the query; denser graphs reduce that risk at the cost of memory and per-hop price, and HNSW’s design is a set of tricks for high recall without density.

The hierarchy: skip lists meet proximity graphs

The “hierarchical” part fixes the slow zoom-in across a large flat graph. During insertion, every vector lands on layer 0, which contains everything. Each higher layer holds a progressively sparser random sample of the same vectors, with membership decided by a decaying probability — exactly like level assignment in a skip list. The top layer might hold a few nodes, the one below a few dozen, and so on down to layer 0 with all of them.

Search enters at the top layer, greedily walks toward the query until it hits a local minimum, then uses that node as the entry point for the layer below, and repeats. The sparse upper layers act as highways: a few long hops move the search into the right region of the space, and the dense lower layers refine it. By layer 0 the search starts from a node already near the answer, so the expensive fine-grained walk is short. Search cost scales roughly logarithmically with collection size — the property that makes vector search at tens of millions of vectors feasible. The full algorithm, including the math behind the layer probabilities, is laid out in the HNSW paper.

How insertion builds the graph

Inserting a vector mirrors searching it. The algorithm greedily descends from the top layer with a candidate list of size 1, then — at the insertion layer — widens the list to a parameter called ef_construction, selects up to M candidates, and links them both ways. Because links are bidirectional, layer-0 nodes can accumulate up to 2 × M edges; higher layers cap at M.

One detail matters more than it looks: HNSW does not simply connect a new vector to its M closest candidates. A diversity heuristic checks each candidate against the neighbors already selected — if the candidate is closer to an already-selected neighbor than to the new vector, it gets skipped. Two nearly identical vectors carry almost the same navigation information, so spending both edge slots on them wastes capacity; diverse edges give the search more distinct escape routes from local minima — a large part of why HNSW beats simpler graph constructions at the same M.

The two build-time parameters interact: M controls the graph’s permanent degree (and therefore its memory footprint), while ef_construction controls how large a candidate pool each insertion considers. Raising ef_construction improves graph quality with diminishing returns — past a few hundred, you pay linearly longer builds for nearly no recall gain. Raising M improves recall on high-dimensional data but grows memory permanently.

Search-time parameters and the pgvector knobs

At query time, the descent through the upper layers still uses a candidate list of size 1, but the final walk on layer 0 keeps a dynamic list of the ef_search best candidates found so far, exploring from the best one each round. It is the single most important runtime knob: it trades query latency for recall, costs no memory, and — unlike M — can change per transaction.

CREATE INDEX ON documents
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);

-- recall too low? raise it, at the cost of latency:
SET hnsw.ef_search = 100;

-- per-query, without touching the session:
BEGIN;
SET LOCAL hnsw.ef_search = 200;
SELECT id FROM documents ORDER BY embedding <=> '[0.13, -0.42, 0.07]' LIMIT 10;
COMMIT;

pgvector defaults to m = 16, ef_construction = 64, and ef_search = 40 — good starting points. Three operational details matter before your first large build:

  • The build speeds up dramatically when the graph fits in maintenance_work_mem; if it does not, PostgreSQL emits a notice partway through and construction slows to a crawl. Raise it for the build session and bump max_parallel_maintenance_workers (default 2) for large backfills.
  • ef_search doubles as a cap on result count. LIMIT 100 with the default ef_search = 40 returns at most 40 rows — the candidate list cannot hold more. Raise LIMIT, raise ef_search to match.
  • Index builds get much faster if you load data first and create the index afterward, and the index can be built on an empty table too — there is no training step, unlike IVFFlat.

Gotchas that bite in production

Filtering happens after the graph walk. A query like “nearest neighbors where tenant_id = 42” does not constrain the search itself — HNSW visits ef_search candidates, and only then applies the predicate. If the filter matches 5% of rows, a candidate list of 40 yields about 2 survivors on average. pgvector 0.8+ addresses this with iterative index scans (SET hnsw.iterative_scan = strict_order), which keep scanning deeper into the graph until enough results pass the filter, bounded by hnsw.max_scan_tuples; partial indexes or list partitioning are the heavier-weight fixes.

Memory grows with degree, not just vector count. The graph stores every edge, so doubling M roughly doubles the per-node link overhead on top of the vector bytes themselves — at billions of vectors, that overhead dominates storage, which is why large deployments pair HNSW with half-precision (halfvec) or binary quantization rather than raising M.

HNSW versus IVFFlat is a build-time/memory trade. IVFFlat clusters vectors with k-means and searches only the nearest few clusters: faster to build and smaller, but a worse speed-recall curve, and it needs existing data before creation because of its training step. For read-heavy workloads with infrequent bulk loads, HNSW is the right default; IVFFlat earns its keep on tight memory budgets.

Wrapping up

HNSW earns its dominance by combining three old ideas — greedy routing, skip-list layering, and edge-selection diversity — into an index whose query cost grows logarithmically with data size while remaining tunable at runtime. The mental model to keep: the hierarchy finds the neighborhood, M decides how well-connected that neighborhood is, ef_search decides how hard to look inside it. Tune ef_search against a measured recall target, size maintenance_work_mem before big builds, and treat filtered vector queries as a different problem than unfiltered ones — those three habits cover most of HNSW’s surprises.

Leave a Reply

Your email address will not be published. Required fields are marked *