Search a graph with a bounded candidate frontier
Separate HNSW hierarchy, base-layer exploration, result count, and implementation-specific search parameters.
On this page
The question for today
What you’ll understand
- Explain the different roles of upper and base layers.
- Trace a local minimum and a wider exploration route.
- Distinguish ef, k, distance evaluations, and exactness guarantees.
Graph retrieval replaces a scan over every stored vector with a walk through selected neighbor links. HNSW organizes those links into a hierarchy: sparse upper layers help find a promising region, and the dense base layer explores nearby alternatives. The useful idea is navigation, not a magic tree that certifies the answer. A graph can direct the walk away from an unseen excellent document, particularly when construction omitted a helpful connection. Search quality therefore depends on both the graph that was built and the amount of exploration allowed during the current query.
Use long routes to approach a local region
In the original HNSW construction, every item appears in the base layer, while progressively fewer items appear in higher layers according to randomly assigned maximum levels. Search begins from an entry point at the top and descends through the hierarchy. Upper-layer greedy moves provide a coarse route across the space. At the bottom, a candidate frontier permits more exploration than following only the single nearest currently visible neighbor. These are graph layers over stored points, not IVF centroid cells.
A strict greedy descent stops when every neighbor of the current point looks worse, even if a path through a slightly worse intermediate point leads to a much better answer. HNSW’s base-layer search retains alternatives to reduce that failure. However, it still examines a bounded portion of the graph under a heuristic stopping rule. Its empirical speed and recall are not an unconditional logarithmic worst-case bound or a proof that every dataset has navigable links.
A frontier budget is not a result count
In hnswlib 0.8.0, ef controls the dynamic list used during search and must be at least k, the requested neighbor count. Larger ef generally trades more query work for better recall; it does not mean exactly ef distance computations. Neighbor expansions, duplicate visits avoided by a visited set, hierarchy traversal, filters, and implementation stopping conditions all influence work. Faiss exposes the related search control as efSearch; do not transfer parameter values between libraries as if they implied identical traversal.
Choose k because the application needs that many unique eligible results, then tune the exploration setting to meet a measured recall target. If the graph or eligible population cannot supply k results, increasing the array size does not create missing neighbors. Different libraries may return sentinels or raise errors for insufficient results. Keep that behavior visible in evaluation and distinguish a short list from a complete list whose IDs are wrong.
Measure navigation failures directly
A useful diagnostic records the exact nearest document, whether it was visited, and where it fell in the approximate results. If it was visited but lost after scoring, inspect the representation or tie policy. If it was never visited, inspect routing and graph construction. Increasing ef on the same frozen graph helps isolate search-budget effects; rebuilding with different construction parameters tests a different hypothesis and should be reported separately.
Queries in sparse regions or unusual clusters can need more exploration than dense mainstream queries. Measure latency distributions and recall by meaningful slices rather than assuming one average describes all routes. Record the implementation version, graph checksum, entry-point state, query metric, and search parameters with each run. Those details turn an attractive single benchmark number into an experiment another engineer can reproduce, including difficult misses rather than only successful paths.
Work it through
A worse intermediate node can lead to the best answer
Consider a toy undirected base graph A—B—C, with q=(0,0), A=(2,0), B=(0,3), and C=(0,1). Start at A. Use squared L2 and compare strict single-point greedy descent with an explicitly exhaustive traversal of this three-node component.
Distances from q are D(A)=4, D(B)=9, and D(C)=1. At A, the only neighbor B is worse, so the simplified greedy rule remains at A. It has no direct information about C because C is not adjacent to A.
For an exhaustive traversal, expand A and then B even though B has distance 9. Expanding B reveals C with distance 1. The visited set now contains all three IDs and can certify the best within this complete three-node component.
For k=1, exact ground truth is {C}. Greedy output {A} has intersection size zero and recall 0; exhaustive output {C} has intersection size one and recall 1. The successful route requires accepting a temporarily worse intermediate distance.
The graph’s path exists, but a strict greedy improvement rule cannot use it. This toy explains why exploration matters; it does not assert a specific ef setting will reproduce this exhaustive traversal in HNSW.
The living notebook
Explore the model
Interactive lab · modular
Reachability differs from repeated stepping
Reset, set Modulus m to 8 and Additive step a to 2. Predict residue 2 after one Step and the orbit {0,2,4,6} with period 4; Step advances one addition. Reset, set m to 8 and a to 3, predict residue 3 after Step and period 8. This additive cycle is a finite reachability analogy, not an HNSW graph or search frontier.
- Residue r0
- 0
- Orbit period · m/gcd(m,a)
- 12
- Distinct residues visited
- 1 of 12
Addition modulo m starts at zero: rₙ = na mod m. Playback advances two additions per second. The orbit has period m/gcd(m,a), including period one for a = 0. This is not a cryptographic security test or a primality algorithm. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forMore time cannot reach vertices outside the chosen transition structure.
Pause & reason
Check your understanding
Your turn
Try it yourself
Ground truth at k=3 is {B,D,F}; a graph search returns {B,C,F}. Compute recall@3. If increasing exploration returns {B,D,F}, what has been shown and what has not?
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Count unique-ID intersection, and limit the conclusion to the measured query and graph.
Compare with the solution
The original intersection is {B,F}, so recall is 2/3. The second result has recall 3/3=1 on this query. It shows the changed search recovered the three reference IDs in this experiment; it does not prove perfect recall for all queries, a universal ef setting, or that the encoder’s geometric neighbors are semantically ideal.
Keep the idea
Take it with you
- Hierarchy improves navigation without certifying unseen distances.
- ef controls exploration; k controls the requested result count.
- Separate unvisited-neighbor misses from scoring and tie errors.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.