HNSW Index Explained: Graph-Based Vector Search

HNSW Index Explained: Graph-Based Vector Search

What do music recommendations, image search, and chatbots that remember context all have in common? Under the hood, most of them lean on a clever data structure called the HNSW index. It is the quiet workhorse that makes fast similarity search possible across millions or even billions of vectors. Yet plenty of engineers use it every day without really knowing what happens when a query hits the index.

This article walks through how HNSW works, why it beats brute-force search, which knobs actually matter, and where it tends to fall short. No math degree required.

What Is the HNSW Index?

HNSW stands for Hierarchical Navigable Small World. It is a graph-based index for approximate nearest neighbor (ANN) search. Instead of comparing a query vector against every stored vector, HNSW hops through a network of connected points, narrowing in on the closest matches step by step.

The method was introduced by Yu. A. Malkov and D. A. Yashunin in a paper first posted in 2016, with a revised version following in 2018. The full algorithm is described in the authors’ original paper on efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs, which remains the best primary source for anyone who wants the details.

The idea builds on the same authors’ earlier work on Navigable Small World graphs. That earlier structure showed you could find near neighbors by following edges across a small-world network. HNSW’s contribution was stacking those networks into layers, which made search dramatically faster.

The Core Idea: A Graph With Layers

The Core Idea: A Graph With Layers

Picture a map of a country. At the coarsest level, you have a handful of major highways connecting big cities. Zoom in, and you get regional roads. Zoom in further, and you have every local street.

HNSW works the same way. Every vector in the index becomes a node in a graph, and nodes are connected to their nearest neighbors by edges. The trick is that the graph has multiple layers:

  • The top layer is sparse, containing only a few nodes connected by long-range links.

  • Each lower layer is denser, adding more nodes and shorter links.

  • The bottom layer contains every single vector in the dataset.

When a new vector is inserted, it gets assigned a maximum layer drawn from an exponentially decaying distribution. Most vectors only exist in the bottom layer. A small fraction reach higher layers, and a tiny handful sit at the very top. This randomness is deliberate: it keeps the upper layers thin and the search cheap.

How a Search Actually Runs

Searching an HNSW index is a two-phase process, and understanding it explains most of the index’s behavior.

  • Enter at the top. The search starts at a fixed entry point in the highest layer.

  • Greedy descent. At each layer, the algorithm moves to whichever neighbor is closer to the query. When no neighbor improves the result, it drops down a layer, keeping the best candidate found so far.

  • Refine at the bottom. Once it reaches the bottom layer, it switches to a broader search, exploring a candidate list of size controlled by the `efSearch` parameter.

  • Return the top results. The closest vectors found become the answer.

The upper layers act as a fast express lane. Because they contain few nodes with long links, the search crosses large distances in a handful of hops. The bottom layer then does the fine-grained work. This layered descent is why search time grows slowly with dataset size rather than linearly.

Why Avoid Comparing Every Vector?

Exact nearest neighbor search, often called brute force or flat search, compares the query against every vector in the dataset. It is perfectly accurate, and for a few thousand vectors it is often fast enough.

The problem is scale. Double the dataset and you double the work. At millions of vectors, a single query can take far too long for a live application.

HNSW trades a small amount of accuracy for an enormous gain in speed. That trade is the whole point of approximate nearest neighbor search: you accept that the index might occasionally miss a true nearest neighbor in exchange for answering in milliseconds.

Feature Flat (exact) search HNSW index
Accuracy 100 percent High but tunable, not guaranteed
Query speed at scale Slow Very fast
Memory use Just the vectors Vectors plus graph links
Build time None Significant
Best for Small datasets, exact needs Large datasets, low latency

That memory overhead is real and worth planning for. Every node stores its neighbor lists, so an HNSW index can need noticeably more RAM than the raw vectors alone. Teams often discover this the hard way when a dataset that fit comfortably in memory suddenly does not.

The Parameters That Matter

HNSW has a small set of parameters, but they drive almost everything about performance. The reference open-source implementation, hnswlib, is a good place to see them named and documented consistently.

M: Connections Per Node

M sets the maximum number of neighbors each node keeps per layer. Higher values create a richer, better-connected graph. That usually means better recall, but also more memory and slower builds. Typical values land between 16 and 64. Going much higher gives diminishing returns while memory costs keep climbing.

efConstruction: Build Quality

efConstruction controls how large a candidate list the algorithm keeps while inserting each new vector. A bigger list means the graph gets built more carefully, with better-chosen neighbors. Builds take longer, but query quality improves. This is a one-time cost, so many teams set it generously.

efSearch: The Query-Time Dial

efSearch is the parameter you will touch most often. It sets the size of the candidate list explored during a query. Raise it and recall improves; lower it and queries get faster. Crucially, it can be changed at query time without rebuilding the index, which makes it a handy lever when latency budgets shift.

A practical habit: tune `efSearch` against your own data and measure recall at your target latency, rather than copying a number from a blog post. The right value depends heavily on your vectors and your accuracy needs.

Where HNSW Fits Among Vector Indexes

HNSW is not the only game in town. Vector databases typically offer several index types, and each makes different trade-offs.

Inverted file (IVF) indexes cluster vectors and only search the closest clusters. They tend to use less memory than HNSW but often deliver lower recall at the same speed.

Product quantization (PQ) compresses vectors into compact codes, slashing memory use at the cost of accuracy. It is often combined with other methods rather than used alone.

HNSW generally delivers high recall at low latency, which is why it became a default choice in many systems. The catch is memory, since the graph lives in RAM.

For an independent view of how these methods compare on recall and latency across real datasets, the ANN benchmarks project publishes reproducible comparisons that are worth checking before committing to an index type.

Practical Tips and Common Mistakes

Knowing the theory is one thing. Getting an HNSW index to behave well in production is another. A few patterns show up again and again.

Do not skip recall measurement. The most common mistake is assuming the index returns perfect results. Build a small ground-truth set with exact search and measure what fraction of true neighbors HNSW actually returns. Without that number, you are flying blind.

Size memory before you load data. Graph links add overhead on top of the vectors themselves. Estimate total memory, add headroom, and test with realistic data volumes. Running out of RAM mid-build is a painful way to learn this lesson.

Treat deletions carefully. HNSW is designed for static or append-heavy workloads. Deleting a node means repairing its neighbors’ links, which is awkward. Many implementations mark deleted items and filter them out at query time, then rebuild periodically to reclaim space. If your data changes constantly, plan for that maintenance.

Normalize vectors consistently. If you use cosine similarity, normalize vectors the same way at index time and query time. Mismatched preprocessing silently wrecks recall, and it is easy to miss because nothing errors out.

Rebuild when the distribution shifts. An index built on last year’s embeddings may not serve this year’s queries well, especially if the model that produces vectors has changed. Version your embeddings and rebuild when the underlying model changes.

Watch the entry point. Some libraries let you set or inspect the entry point node. If it drifts far from the data’s center of mass, early search steps get less efficient. Most implementations handle this automatically, but it is worth knowing the concept exists.

When HNSW Is the Wrong Choice

HNSW is excellent, but it is not universal. It is a poor fit when you need guaranteed exact results, when memory is severely constrained, or when your dataset is small enough that brute force is already fast. It also struggles with workloads that demand frequent, arbitrary deletions without periodic rebuilds.

For teams managing large retrieval systems, reviewing how indexes are accessed and maintained is part of keeping search healthy over time. A structured approach to reviewing access to a retrieval index helps catch configuration drift, stale data, and permission gaps before they affect users. Keeping an eye on news about search and retrieval tooling also helps teams track how implementations evolve, while deeper technical write-ups often appear in a blog covering indexing and infrastructure topics.

Conclusion

The HNSW index is one of those ideas that looks complicated from the outside and feels obvious once you see the layers. By building a hierarchy of proximity graphs and descending greedily from sparse to dense, it finds near neighbors in roughly logarithmic time instead of scanning everything. The cost is memory and a tunable loss of exactness, a trade most large-scale search systems happily make.

If you take one thing away, make it this: HNSW rewards measurement. Understand `M`, `efConstruction`, and `efSearch`, then tune them against your own data and your own latency budget. The defaults are a starting line, not a finish line.

What does HNSW stand for?

HNSW stands for Hierarchical Navigable Small World. The name describes the structure: a hierarchy of graph layers where each layer is a navigable small-world network, meaning any node can be reached from any other in a small number of hops.

Is HNSW exact or approximate?

HNSW is approximate. It does not guarantee that it will find the true nearest neighbors every time. Instead, it finds very close matches with high probability, and the recall rate can be tuned through parameters like `efSearch`. For most applications, that trade-off is well worth the speed gain.

What is the difference between efConstruction and efSearch?

`efConstruction` controls how thoroughly the graph is built during insertion. It affects build time and index quality but has no effect on query speed once the index exists. `efSearch` controls how broadly the index explores during a query. It affects recall and latency at query time and can be adjusted without rebuilding.

How much memory does an HNSW index need?

It depends on the number of vectors, their dimensions, and the value of `M`. The raw vectors take the same space as always, but the graph adds neighbor lists on top. Higher `M` values mean more links and more memory. Always estimate total memory with realistic data before deploying.

Can I delete vectors from an HNSW index?

Deletion is one of HNSW’s weaker areas. Removing a node requires repairing the links of its neighbors, which is complex. Many implementations mark items as deleted and filter them during queries, then rebuild the index periodically to reclaim space. Workloads with heavy churn need a maintenance plan.

Why does HNSW sometimes return different results for the same query?

If the index is being updated concurrently, or if `efSearch` is set low, results can vary between runs. Approximate search explores a limited candidate set, so small changes in the graph or the search budget can shift which neighbors surface. Raising `efSearch` generally makes results more stable.

Latest articles

Scroll to Top