The Retrieval Bench

hnsw for Practical Vector Search: A Reproducible Guide

hnsw for Practical Vector Search: A Reproducible Guide
hnsw explained for practical vector search: learn how the index works and how to test recall, latency, memory, and build cost with local embeddings.

Here is the short version: hnsw is a graph-based approximate nearest-neighbor index that can make vector search fast without comparing a query against every stored embedding. It is useful for semantic search, retrieval-augmented generation, and local document systems, but it is not a magic quality switch. Its behavior depends on the embedding model, distance metric, graph parameters, hardware, and query workload.

If you are testing EmbeddingGemma 2 on a small workstation, hnsw is a sensible first index to measure. It usually gives a practical balance between recall, latency, memory, and implementation effort. The important word is measure. A result from one million random vectors on a desktop does not automatically predict the behavior of a private document collection on a laptop.

What hnsw actually does

The name refers to a hierarchical navigable small-world graph. Instead of organizing vectors in a simple tree, the index connects nearby points through layers of links. The upper layers are sparse and help the search move quickly across the space. The lower layer contains more connections and provides a closer search among promising candidates.

At query time, the index begins with an entry point near the top. It follows links that improve similarity, descends through the hierarchy, and then explores a controlled neighborhood on the bottom layer. Because it does not inspect every vector, the search is approximate. You trade some exactness for lower latency.

That trade is adjustable. The parameter often called efSearch controls how many candidates the query considers during search. A larger value generally improves recall, but it also consumes more CPU time. M controls the number of graph connections per node. A larger M can improve navigability, while increasing index size and construction cost. The build parameter, commonly called efConstruction, affects how carefully links are selected while the graph is created.

Different libraries expose these settings differently, so record the actual configuration rather than copying a parameter name into a spreadsheet. Faiss, hnswlib, Qdrant, Weaviate, and other systems may apply defaults and memory layouts in different ways.

Illustration for hnsw

A small, reproducible experiment

I would start with a fixed corpus rather than a large production dataset. Use a few thousand to a few hundred thousand text chunks from public documentation or a synthetic collection with known relevant passages. Keep chunk size, overlap, normalization, and embedding model constant. If you change all four at once, you will not know why the result moved.

Generate embeddings with the same EmbeddingGemma 2 configuration for every index. Store the vectors in float32 for the first run, then test reduced precision only after establishing a baseline. Normalize vectors if your comparison uses cosine similarity, and verify that the database applies the metric you intended. A cosine experiment accidentally configured as Euclidean distance can look like a model failure.

For each query, create a small relevance set. You can label the top results manually or use a question-to-document mapping when the collection is synthetic. Report recall at 10, median latency, p95 latency, index build time, and resident memory. Recall at 10 answers a simple question: did the relevant item appear in the first ten results? Median latency describes the typical query, while p95 exposes the slower tail that users notice during bursts.

Run at least three repetitions after warming the index. Record CPU model, RAM, operating system, thread count, vector count, and whether the process is competing with other workloads. On a home server, a background backup can distort a five-minute benchmark. The benchmark is the conversation starter, not the verdict.

Choosing parameters without guessing

A useful starting sweep might hold M at 16 and test efSearch values of 32, 64, 128, and 256. Then repeat with M at 32 if the memory increase is acceptable. This is not a universal recommendation; it is a compact experiment that shows the shape of the trade-off. If recall rises sharply from 32 to 64 but barely changes at 128, the additional search work may not justify the latency.

The same hnsw setting can behave differently after changing embeddings. A model that produces tightly clustered representations may need more exploration than one whose relevant items are easier to separate. Document length matters too. Short product titles, long legal paragraphs, source-code functions, and support tickets create different neighborhoods.

Build settings deserve separate attention. Higher efConstruction can produce a better graph, but it makes ingestion slower. That cost matters when documents change frequently. For a weekly batch import, spending extra time during construction may be reasonable. For a continuously updated support system, an incremental workflow with simpler construction may be more practical.

Memory is another constraint. The graph stores links in addition to the vectors and metadata. At larger scale, the links and allocator overhead become material, especially when vectors remain in float32. Measure the process resident set after loading and after several queries; do not estimate memory from vector bytes alone.

Visual context for hnsw

hnsw compared with simpler baselines

Always compare hnsw with exact search on the same vectors. Exact search is often dismissed as too slow, but it is the quality reference for a small collection. If exact search takes 20 milliseconds for 50,000 vectors on your machine, an approximate index may add maintenance complexity without improving the product.

BM25 is another required baseline for text retrieval. Dense embeddings can retrieve conceptually related wording, while BM25 often handles names, identifiers, error codes, and exact phrases better. A hybrid system that combines BM25 and hnsw can outperform either method on mixed technical content, but fusion adds tuning and another failure surface.

Measure the embedding model separately from the index. If hnsw and exact search produce nearly identical recall, the index is probably not the problem. If both fail to retrieve the right passage, changing efSearch will not repair weak chunking or an unsuitable embedding model. This is where the simple baseline earns its keep.

Common failure modes in local deployments

One failure mode is benchmarking only average latency. A fast average can hide occasional pauses from memory pressure, garbage collection, page faults, or concurrent embedding work. Capture p95 and, when the application is interactive, p99 as well.

Another is rebuilding the graph every time a document changes. Frequent updates can make build time and operational complexity more important than raw query speed. Consider separating ingestion from serving, batching updates, and measuring how much quality changes after additions. Deletions also deserve a test because some implementations mark entries rather than compacting the underlying structure immediately.

Do not assume more links always mean better search. A larger M increases memory and can make construction expensive. It may improve recall on one corpus while producing little benefit on another. Similarly, raising efSearch indefinitely can turn an approximate index into an expensive partial scan without matching the quality of exact search.

A practical decision for EmbeddingGemma 2

For a private document search prototype, I would use exact search as the reference, hnsw as the first approximate candidate, and BM25 as the lexical comparison. Start with a modest corpus and a reproducible query set. Record the full configuration in a README, including the embedding model revision, distance metric, chunking rules, index parameters, hardware, and software versions.

Move forward when the index meets a measured recall target and produces useful p95 latency on the intended machine. Stay with exact search when the collection is small or when simplicity matters more than a few milliseconds. Add hybrid retrieval when queries include technical tokens, product names, or exact identifiers that dense search misses.

The result is useful, but narrower than it first appears: hnsw is an efficient search mechanism, not a substitute for evaluation. Run the comparison, keep the failed configurations, and let the workload decide. A quiet local machine and a clear experiment often reveal more than a larger hosted benchmark.

Updated · 2026-10-29 21:38
Feedback

No feedback yet — submit the first.

Submit feedback
© 2026 Semantic Workshop. All rights reserved. data-driven, published weekly ♥