Subscribe
AI
6 min read

What Is HNSW? The Graph Index That Runs Your Vector Search

Embeddings turned retrieval into geometry, and geometry needs an index. Hierarchical Navigable Small World graphs are the approximate nearest neighbor method inside Weaviate, Qdrant, FAISS and pgvector, and they are why a RAG query returns in milliseconds instead of minutes.

Title card reading What Is HNSW with a layered network of connected nodes behind it
Title card reading What Is HNSW with a layered network of connected nodes behind it

Every RAG tutorial ends with the same sentence: embed your documents, store the vectors, retrieve the closest ones. Nobody stops at the verb. Closest to what, out of how many? A query embedding compared against every stored embedding is a full scan, and at ten million vectors a full scan is not a retrieval step, it is a nightly batch job. So what runs at query time inside Weaviate, Qdrant and Postgres is an algorithm most product pages never name: Hierarchical Navigable Small World graphs, or HNSW.

The problem HNSW solves

Language models turn text into a vector, typically several hundred to a few thousand dimensions. Finding the k most similar stored vectors to a query vector means computing k-nearest neighbors in that space, and exact search in high dimensions gets slow for two reasons: every comparison touches all the dimensions, and there is no clever way to prune. Most dimensions of an embedding carry signal, so the space cannot be subdivided the way a database index subdivides numbers on a line.

The standard escape hatch is to stop promising exact answers. Approximate nearest neighbor (ANN) search returns the neighbors it can find fast, and reports quality as recall: the fraction of true top-k that show up in the result. Every ANN method is a bet that you can trade a few percent of recall for two or three orders of magnitude of latency. HNSW is the method that has mostly won that bet in production.

What the graph is

HNSW, introduced in 2016 by Yury Malkov and Dmitry Yashunin (arXiv 1603.09320), organizes all stored vectors as nodes in a graph. Each node keeps links to vectors that were near it when it was inserted. To search, you enter the graph at some node, compute the distance from there to your query, and hop to whichever neighbor is closer. Repeat until no neighbor beats your current position. This greedy walk needs only a few hundred distance computations, not ten million, because each hop buys you proximity to the answer.

Greedy nearest-neighbor walk: each hop lands closer to the target cluster in a dense vector graph.

Plain greedy walks on proximity graphs were the older generation of this idea, under the name navigable small world graphs. Their weakness was the entry point: start far from the query, in a dense local neighborhood, and the walk crawls. Malkov and Yashunin fixed that with hierarchy. Each vector is assigned a maximum layer randomly, with a geometrically decaying probability, so a few vectors live in many layers and most live only in the bottom one. The top layer is a sparse graph of long links that spans the whole space; layer zero is the dense graph of short links where the real neighbors live. Search descends from the top layer, greedy walk at each level, using the current best node as the entry point of the layer below. Long hops first, short hops last. The authors describe the structure as analogous to a skip list, and it scales the number of hops logarithmically with dataset size, which is the property that makes billion-vector indexes practical. A heuristic for choosing which links to keep, added in the same paper, preserves link diversity instead of taking the k closest candidates, and is what keeps recall high on clustered data.

Three-layer HNSW graph: sparse long links on top, dense short links at the bottom, with a search path descending layer by layer.

The knobs

Implementations expose three parameters, and every vector database dashboard is a re-skin of these three:

  • M: the number of links per node. More links raise recall and query speed at the cost of memory (roughly linear in M) and slower index builds. Qdrant documents the trade-off directly.
  • ef_construction: how many candidate neighbors the builder considers when inserting each vector. Higher builds a better graph and takes longer.
  • ef_search (pgvector calls it hnsw.ef_search, Qdrant hnsw_ef): how many candidates the greedy best-first search keeps on its open list at the bottom layer. This is the dial you turn when you need more recall at query time. The pgvector 0.5.0 guide gives the practical floor: ef_search must be at least as large as the LIMIT you want back.

Build cost is the parameter nobody advertises. Inserting every vector means running a full graph search plus link rewiring per item, so HNSW indexes are slow to construct, which is why Weaviate ships a dynamic mode that stays flat-exhaustive until 10,000 objects and converts to HNSW in the background (Weaviate vector index docs).

Who actually runs this

The reference implementation is hnswlib, a header-only C++ library with Python bindings from Malkov, carrying about 5.4k stars on GitHub. Meta's FAISS, the vector search library most of the research world learned on, includes HNSW as an index type. Among databases, it is closer to a default than an option:

  • Weaviate sets vectorIndexType to hnsw out of the box.
  • pgvector 0.5.0, the extension that brought vector search to ordinary Postgres, added HNSW in August 2023 alongside IVFFlat, and Cloud SQL, Aurora and Neon all shipped it.
  • Qdrant extends the core graph with filter-aware edges so metadata filters (the permission checks of enterprise RAG) do not force a full scan.

The practical consequence for anyone building on embeddings: the recall you measure in your eval is mostly recall of this algorithm, and the memory bill of your vector database is dominated by keeping the graph in RAM.

How it was benchmarked, and where it breaks

Fair comparison of ANN methods is itself a research contribution: ANN-Benchmarks (Aumuller et al., 2018) standardized recall-versus-latency curves across implementations on common datasets, and HNSW-family indexes top most of those charts at high recall. Independent studies also show the limits. A 2024 paper found that recall depends on the order in which data was inserted and on the intrinsic dimensionality of the embedding set, so an index tuned on one corpus can degrade quietly as your data shifts. And the memory-bound design drew a serious challenger: Microsoft's DiskANN (Subramanya et al., NeurIPS 2019) reported indexing a billion points on a single 64GB machine plus an SSD, and in the high-recall regime serving 5 to 10 times more points per node than in-memory graph methods such as HNSW, at the cost of disk reads per query. The ongoing engineering argument is exactly where those points sit: HNSW says keep the graph in RAM and buy faster queries, DiskANN-style designs say pay for SSD bandwidth and save on memory.

Two failure modes are worth knowing before you ship. First, approximation is invisible: HNSW queries return plausible results with no signal that recall dropped, and pgvector notes flat out that unlike a b-tree, an HNSW index can give different results for the same query. Second, deletes and updates fight the graph. The hnswlib README documents deletion as a marking operation: a marked element is omitted from results but stays in the index, and its memory is reclaimed only if you enable replacing deleted elements on later inserts. A collection with heavy turnover accumulates dead weight until the index is rebuilt.

The one-paragraph version

Embeddings turn retrieval into geometry, and geometry needs an index. HNSW builds a layered graph over the vectors: sparse long links on top, dense short links on the bottom, a greedy walk down through the layers, and three knobs (M, ef_construction, ef_search) that trade memory, build time and recall for latency. It scaled logarithmically when its predecessors scaled badly, it shipped into FAISS, hnswlib, Weaviate, Qdrant and Postgres, and it is the reason a RAG app answers in milliseconds instead of minutes. It also gives approximate answers without announcing it, so the recall number you tune against is the product.

Sources

AILLMeducational