How does HNSW work?
- Authors
- Name
- Amit Shekhar
- Published on
HNSW is a way of finding the most similar items in a huge collection very quickly. It connects similar items to each other like a network of roads, stacks a few layers of these networks on top of each other, and then jumps from far to near, just like we take a flight, then a highway, and then a local road to reach a house.
In this blog, we will learn about how HNSW works. We will also see why checking every vector is too slow, how a graph of neighbors and layers borrowed from the skip list make search fast, how HNSW searches and adds vectors step by step, what the settings M, efConstruction, and efSearch control, and where it works well and where it fails.
We will cover the following:
- What is similarity search?
- The problem: checking every vector is too slow
- What is Approximate Nearest Neighbor search?
- Idea 1: A graph of neighbors
- The problem with a single graph
- Idea 2: Layers, borrowed from the skip list
- What is HNSW?
- How does search work in HNSW?
- How does HNSW add a new vector?
- The important settings: M, efConstruction, and efSearch
- HNSW in code
- Brute force vs HNSW
- Where HNSW works well and where it fails
I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.
I teach AI and Machine Learning at Outcome School.
Let's get started.
What is similarity search?
Before jumping into HNSW, we must know what similarity search is, because HNSW is built to do it fast.
In AI, we use embedding models that turn text, images, or songs into vectors, which are lists of numbers. These vectors are called embeddings. Things with similar meaning get vectors that are close to each other. "I love dogs" and "Puppies are my favorite" get close vectors, while "The stock market fell" gets a far away vector.
Similarity search means finding the vectors in our collection that are closest to a given vector.
The given vector is called the query. The closest vectors are called its nearest neighbors.
Let's say we describe fruits with two numbers: how sweet they are and how big they are, each from 0 to 10.
Apple -> [7, 4]
Mango -> [9, 5]
Watermelon -> [6, 10]
Lemon -> [1, 3]
Here, each fruit is a vector of 2 numbers, and we can draw them as points on a paper. Now, let's say we have a new fruit with vector [8, 5]. Its nearest neighbor is Mango [9, 5], because it is the closest point on the paper.
Real embeddings have hundreds or thousands of numbers, not just 2. But for the sake of understanding, we will imagine them as points on a paper.
The closeness is measured with a distance, like the straight-line distance between two points. Smaller distance means more similar. We have a detailed blog on Cosine Similarity that explains another popular way to measure how close two vectors are.
Similarity search is used everywhere:
- Finding documents for a question in a RAG system, which gives the right text to an LLM.
- Recommending similar products, songs, or movies.
- Finding similar images.
We have a detailed blog on how Semantic Search works that covers this end to end for text.
The problem: checking every vector is too slow
The simplest way is to measure the distance from the query to every vector in our collection, and pick the smallest. This is called brute force search.
With 100 vectors, this is fine. But real systems can have 100 million vectors, each with 1000 numbers. For every single search, we would do 100 million distance calculations. That is far too slow when users expect an answer in a few milliseconds.
So, the question is: can we find the closest vectors without checking all of them?
What is Approximate Nearest Neighbor search?
The answer is yes, if we agree to a small trade-off.
Approximate Nearest Neighbor search, or ANN, finds vectors that are very close to the query, almost always the true closest ones, but much faster than checking everything.
This means we accept that once in a while we will miss one of the true closest vectors, and in return, we get a search that is often hundreds or thousands of times faster.
How often we find the true closest vectors is called recall. A recall of 0.95 means that, out of every 100 true nearest neighbors, we found 95.
HNSW is one of the most popular ANN methods. It is used inside many vector databases and libraries like FAISS and Qdrant.
Now, let's build HNSW step by step, one idea at a time.
Idea 1: A graph of neighbors
First, let's understand what a graph is.
A graph is a set of points connected by lines. The points are called nodes, and the lines are called edges.
We make every vector a node, and we connect each node to a few of its closest nodes with edges. Now, each vector "knows" its neighbors.
A ------ B ------ C
| | |
D ------ E ------ F ------ G
| | |
H ------ I ------ J
To search, we do greedy search:
Step 1: Start from some node, called the entry point.
Step 2: Look at all its neighbors and measure their distance to the query.
Step 3: Move to the neighbor that is closest to the query.
Step 4: Repeat. When no neighbor is closer than the current node, stop. This is our answer.
It is like asking for directions in a new city. We ask a person, "Which way to the railway station?". They point us to a closer street. We ask again there. Each step brings us closer. We never need to visit every street.
This is much faster than brute force. We only check the neighbors of the nodes on our path.
Planning your move into AI?
No matter which tech domain you work in today, with your effort, you can transition to these roles:
- AI Engineer
- Forward Deployed Engineer
- AI Agent Engineer
- Harness Engineer
- Voice AI Engineer
- AI Architect
- LLM Engineer
- LLM Inference Engineer
- Gen AI Engineer
- MLOps Engineer
- ML Engineer
- Deep Learning Engineer
Our AI and Machine Learning Program at Outcome School takes you there.
The problem with a single graph
With a single graph, two problems arise:
- Too many small steps: If every node only connects to its nearby nodes, going from one side of the collection to the other side takes a very long path, one small step at a time.
- Getting stuck: Greedy search can stop at a node where no neighbor is closer, even though the true closest node is somewhere else. This is called getting stuck in a local minimum.
We need a way to make big jumps first, and small careful steps at the end.
Idea 2: Layers, borrowed from the skip list
Before jumping into the solution, we must know about a simple structure called a skip list.
A skip list is a sorted list with extra "express" lanes on top that skip over many items.
Let's say we have sorted numbers from 1 to 100. To find 73 in a normal list, we walk one by one. In a skip list, we have layers:
Layer 2: 1 ---------------------- 50 ---------------------------- 100
Layer 1: 1 ----------- 25 ------- 50 ----------------- 75 ------- 100
Layer 0: 1 - 2 - ... - 25 - ... - 50 - ... - 73 - 74 - 75 - ... - 100
We start at the top layer and take big jumps: 1, then 50. The next jump on layer 2 goes to 100, which is too far. So, we go down to layer 1 and continue from 50: the next stop, 75, is too far, so we go down to layer 0 and walk 50, 51, ..., 73. The top layers skip a big part of the work.
It is exactly like a metro system with express trains and local trains. The express train stops at a few big stations. The local train stops at every station. We take the express to get near, then the local to reach exactly.
Now, what if we build a skip list, but each layer is a graph of neighbors instead of a list?
What is HNSW?
HNSW stands for Hierarchical Navigable Small World. It is a multi-layer graph where the top layers have few nodes with long jumps, and the bottom layer has all nodes with short, local connections.
Let's break the name:
HNSW = Hierarchical + Navigable + Small World
- Small World: A network where any two points are connected by just a few hops, like how any two people in the world are connected through a few friends.
- Navigable: We can find our way through it with simple greedy steps, without a map of the whole network.
- Hierarchical: It has layers, from a small top layer to a full bottom layer.
HNSW was introduced by Yury Malkov and Dmitry Yashunin in a research paper in 2016.
It looks like below:
Layer 2: A --------------------------------- J (very few nodes)
| |
Layer 1: A ------------- E ----- G --------- J (some nodes)
| | | |
Layer 0: A - B - C - D - E - F - G - H - I - J (all nodes)
Here, we can see that:
- Layer 0 (the bottom) has every vector.
- Each higher layer has fewer vectors.
- A vector that appears in a higher layer also appears in all the layers below it.
- The vertical lines show the same node in different layers.
How does HNSW decide which vectors go to the higher layers? It is random, like a coin toss with fewer and fewer winners. Every vector is in layer 0. A smaller share of them also gets into layer 1. An even smaller share gets into layer 2, and so on. So, the top layers stay small, just like the express lanes in a skip list.
Because the top layers have few nodes spread across the whole collection, their edges naturally connect far away points. These are our long jumps. The bottom layer has all the nodes, so its edges connect close points. These are our careful small steps.
A quick note for you
No matter which tech domain you work in, get familiar with these topics:
- LLM
- RAG
- MCP
- Agent
- Fine-tuning
- Quantization
We put it all together in one video:
AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization
No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.
Now, let's get back to the topic.
How does search work in HNSW?
Now, let's see how HNSW finds the nearest neighbors of a query.
Step 1: Start at a fixed entry point in the top layer.
Step 2: Do greedy search in this layer. Keep moving to the neighbor closest to the query until no neighbor is closer.
Step 3: Go down one layer, starting from the node where we stopped.
Step 4: Repeat the greedy search in this layer, then go down again.
Step 5: In layer 0, do a more careful search. Instead of following only one best node, keep a list of the best few candidates found so far, and explore their neighbors too. The size of this list is called efSearch.
Step 6: Return the closest k vectors from that list.
Let's see it like below:
Query: Q (somewhere near node H)
Layer 2: A ---> J (big jump towards Q)
↓
Layer 1: J ---> G (medium jump)
↓
Layer 0: G ---> H (small careful steps, H is closest)
Here, we can notice that we reached the right area of the collection in just a few hops on the top layers. Only at the bottom, we did the careful work. And the careful search with a list of candidates, not just one, greatly reduces the chance of getting stuck in a local minimum.
How does HNSW add a new vector?
Now, let's understand how the graph is built. HNSW builds the graph by adding vectors one at a time.
Step 1: Pick a random top layer for the new vector, using the coin toss idea. Most vectors get only layer 0.
Step 2: Starting from the entry point at the very top, do greedy search down to the new vector's top layer, just like a search, to find where it belongs.
Step 3: From its top layer down to layer 0, search for its closest nodes in each layer. The size of the candidate list during this search is called efConstruction.
Step 4: Connect the new vector to up to M good neighbors in each layer.
Step 5: If a neighbor now has too many connections, remove its weakest ones to keep the graph tidy.
If the new vector got a higher layer than every vector before it, it becomes the new entry point at the top.
Note: When choosing neighbors, HNSW does not always pick the plain closest ones. It prefers neighbors in different directions, so that the node gets "roads" leading in many directions instead of many roads all leading the same way. This keeps the graph easy to navigate.
To master Vector Databases, Embeddings, and AI and ML System Design, we can join our AI and Machine Learning Program at Outcome School.
The important settings: M, efConstruction, and efSearch
HNSW has three main settings that we tune based on our use case:
- M: The number of neighbors each node connects to in each layer. Layer 0 usually allows double, which is
2 * M. BiggerMmeans better recall, but more memory and slower building. Common values are between 8 and 64, and 16 is a popular default. - efConstruction: How many candidates we look at while adding a vector. Bigger means a better quality graph, but slower building. It does not affect search speed directly. Values like 100 to 400 are common.
- efSearch: How many candidates we keep while searching layer 0. Bigger means better recall, but slower search. It must be at least
k, the number of results we want. The best part is that we can change it at search time without rebuilding.
Let's say our search gives a recall of 0.90 and we want 0.97. We can increase efSearch. If that is not enough, we rebuild with a bigger M or efConstruction.
HNSW in code
Now, let's see the code using hnswlib, a popular Python library for HNSW.
import hnswlib
import numpy as np
dim = 128
data = np.random.random((10000, dim)).astype('float32')
index = hnswlib.Index(space='l2', dim=dim)
index.init_index(max_elements=10000, ef_construction=200, M=16)
index.add_items(data, np.arange(10000))
index.set_ef(50)
labels, distances = index.knn_query(data[:1], k=5)
print(labels)
Here, we have:
datais 10,000 random vectors, each with 128 numbers. In a real system, these would be embeddings.hnswlib.Index(space='l2', dim=dim)creates an empty HNSW index.l2means squared straight-line distance, which gives the same ranking as plain straight-line distance.init_index(...)sets the maximum number of vectors,ef_construction, andM.add_items(...)inserts all the vectors and builds the layered graph.set_ef(50)setsefSearchto 50.knn_query(data[:1], k=5)finds the 5 nearest neighbors of the first vector.
The result will be an array of 5 ids. Since we searched with a vector that is already in the index, its own id almost always comes first, with distance 0.
Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.
Brute force vs HNSW
Let me tabulate the differences between brute force search and HNSW for your better understanding.
| Point | Brute force | HNSW |
|---|---|---|
| How it searches | Checks every vector | Hops through a layered graph |
| Speed on huge data | Very slow | Very fast |
| Result | Always exact | Approximate, with high recall |
| Extra memory | None | Stores the graph edges |
| Build time | None | Needs time to build the graph |
| Tunable | No | Yes, with M, efConstruction, efSearch |
| Best for | Small collections | Medium to very large collections |
Where HNSW works well and where it fails
Advantages:
- It is very fast, and the search time grows slowly even when the collection grows very big.
- It gives high recall, often above 0.95, with sensible settings.
- We can add new vectors at any time without rebuilding everything.
- We can trade speed for accuracy at search time by changing
efSearch.
Disadvantages:
- It uses a lot of memory, because it stores the vectors and all the edges, usually in RAM.
- Building the graph for a huge collection takes time.
- Deleting vectors is tricky. Most libraries only mark them as deleted, and the graph slowly becomes less tidy.
- Filtering, like "only products under 500 rupees", is not natural for it, and it needs extra tricks to work well.
Now, we must have understood how HNSW works, how it searches and adds vectors, and where it works well and where it fails.
Frequently Asked Questions
Is HNSW search exact?
No. HNSW is an Approximate Nearest Neighbor method, so once in a while it can miss one of the true closest vectors. In return, it is often hundreds or thousands of times faster than brute force. With sensible settings, its recall is often above 0.95, which means it finds almost all of the true nearest neighbors.
Why does HNSW use so much memory?
HNSW stores the vectors and all the graph edges, usually in RAM. Each node connects to up to M neighbors in each layer, and layer 0 usually allows double that. So, a bigger M gives better recall but uses more memory. Brute force needs no extra memory because it has no graph to store.
Can we add new vectors to an HNSW index without rebuilding it?
Yes. HNSW builds its graph by adding vectors one at a time, so we can add new vectors at any time without rebuilding everything. Deleting is harder: most libraries only mark a vector as deleted, and the graph slowly becomes less tidy over time.
How do we improve recall in HNSW?
The easiest way is to increase efSearch, which we can change at search time without rebuilding the index. A bigger efSearch keeps more candidates in layer 0, so recall goes up but search gets slower. If that is not enough, we rebuild the index with a bigger M or efConstruction.
That's it for now.
Thanks
Amit Shekhar
Founder @ Outcome School
You can connect with me on:
Follow Outcome School on:
