Sweep search ef on your current HNSW index first. It can change recall and p99 latency without rebuilding the graph. Try new M values if no search setting meets both targets, or if the graph exceeds your size or memory budget. Sweep ef for each candidate M, then pick the smallest index that meets your limits.
What M actually is
M controls graph connectivity at build time. A higher M gives new vectors more links, which can help recall on data with high intrinsic dimensionality, at a memory cost. hnswlib estimates the graph cost at roughly M × 8–10 bytes per stored vector. Search ef controls the size of the candidate list during queries. Increasing it can improve recall at the cost of query time while leaving the graph size fixed. hnswlib parameter notes
If the current graph fits but misses recall at the highest ef your latency budget allows, try a larger M. If the graph is too large, try smaller M values and see whether a wider search can recover recall within the latency limit.
Where the knob lives, per engine
| Engine | M setting | How to evaluate a different M |
|---|---|---|
| hnswlib | M in init_index |
Build a candidate index. On the current graph, use set_ef to change search breadth. Python bindings |
| Faiss | The number in an index factory string such as HNSW32 |
Create a candidate with the desired link count in the factory string. Faiss index factory |
| pgvector | m in the HNSW index options |
Create a candidate with WITH (m = ...). pgvector HNSW docs |
| Qdrant | hnsw_config.m |
Update the collection configuration. The optimizer rebuilds affected segments in the background. Benchmark after it finishes. Collection updates, optimizer |
| Weaviate | maxConnections |
Use a new collection for a different value. The setting is fixed after creation. Vector index settings |
| Milvus | M in the HNSW build parameters |
Set M when defining the parameters for a candidate index build. Milvus HNSW docs |
| Elasticsearch | index_options.m |
Use a fresh index for a uniform comparison. Supported HNSW type transitions allow M to stay the same or rise, and existing vectors keep their original index type until their segments are rebuilt. Dense vector reference |
| OpenSearch | method.parameters.m |
Create a new index with the target HNSW mapping. The M setting is fixed after index creation. Methods and engines |
The metric that matters
Use one row per M and search ef pair. Its recall@k is the average fraction of exact top-k labels recovered for each query. For each row, record p99 query time and the saved bytes per vector. hnswlib exact recall example
- Freeze the corpus snapshot, labels, distance, preprocessing and k. Use the same held-out queries in the same order for every row.
- Set the recall floor, p99 ceiling and saved index size limit before the sweep. Use a separate RAM cap if memory is the constraint. Vector database memory sizing
- Keep the machine, warmup, query concurrency and offered load the same across rows. For candidate builds, keep the insertion order, build threads, random seed and
ef_constructionfixed. - Compute exact top-k once with
BFIndexon the same vectors and labels. For each query, count the intersection of the returned and exact labels, then divide by k. Recall@k benchmark guide
Wiring it up
Set up the inputs in a Python session with hnswlib and NumPy available.
xbis the corpus array in build order, andidscontains its unique nonnegative integer labels.xqis the nonempty held-out query array.warmup_queriescontains the separate warmup queries. Use NumPy float32 arrays with the same vector width.current_pathpoints to a trusted, saved hnswlib index for that snapshot. This loop assumes an unfiltered workload and an index with no deleted entries. Setspaceto the distance used to build it (l2,iporcosine). Setkto your result count, between one and the corpus size.ef_valuesis a list of search settings between k and the corpus size. Include the live value from your serving config, since hnswlib does not save it with the index.m_valuesis a nonempty list of candidate link counts, including the current M for a fresh-build comparison.recall_floor,p99_limit_msandsize_limit_bytesare your limits. The code times one query at a time after warmup. For a serving p99 limit, replay the same query sequence at the target request rate and concurrency for each candidate. Apply the latency gate to p99 measured from request start to response. Search ef tuning guide
The loop uses Python’s performance counter for elapsed time and NumPy’s percentile for p99. It measures candidate files in a temporary directory with Python’s file size function.
from os.path import getsize, join
from tempfile import TemporaryDirectory
from time import perf_counter
import hnswlib
import numpy as np
count, dim = xb.shape
exact = hnswlib.BFIndex(space=space, dim=dim)
exact.init_index(max_elements=count)
exact.add_items(xb, ids)
exact_labels, _ = exact.knn_query(xq, k=k)
truth = [set(labels) for labels in exact_labels]
del exact
def sweep(index, saved_bytes, build_s):
for ef in ef_values:
index.set_ef(ef)
for query in warmup_queries:
index.knn_query(query[None, :], k=k, num_threads=1)
hits = 0
times_ms = []
for query, expected in zip(xq, truth):
batch = query[None, :]
start = perf_counter()
labels, _ = index.knn_query(batch, k=k, num_threads=1)
times_ms.append((perf_counter() - start) * 1000)
hits += len(set(labels[0]) & expected)
yield {
"M": index.M,
"ef": ef,
"ef_construction": index.ef_construction,
"recall": hits / (k * len(xq)),
"p99_ms": float(np.percentile(times_ms, 99)),
"build_s": build_s,
"saved_bytes": saved_bytes,
"bytes_per_vector": saved_bytes / count,
}
def build_and_sweep(m, construction_ef):
start = perf_counter()
index = hnswlib.Index(space=space, dim=dim)
index.init_index(max_elements=count, M=m, ef_construction=construction_ef)
index.add_items(xb, ids, num_threads=1)
build_s = perf_counter() - start
with TemporaryDirectory() as folder:
path = join(folder, "candidate.bin")
index.save_index(path)
return list(sweep(index, getsize(path), build_s))
def choose(rows):
passing = [
row for row in rows
if row["recall"] >= recall_floor
and row["p99_ms"] <= p99_limit_ms
and row["saved_bytes"] <= size_limit_bytes
]
return min(passing, key=lambda row: (row["saved_bytes"], row["p99_ms"]), default=None)
current = hnswlib.Index(space=space, dim=dim)
current.load_index(current_path)
construction_ef = max(current.ef_construction, max(m_values))
rows = list(sweep(current, getsize(current_path), build_s=None))
del current
if choose(rows) is None:
for m in m_values:
rows.extend(build_and_sweep(m, construction_ef))
for row in rows:
print(row)
print("Selected:", choose(rows))
hnswlib raises the effective ef_construction to at least M. The loop picks a shared value at or above the largest candidate M so each fresh build uses the same construction breadth. Also run the candidate loop if you want a smaller graph or if the current graph passes the serial check but fails under serving load. hnswlib graph constructor
What you’ll see
| M | Search ef | Recall@k | p99 (ms) | Build time (s) | Saved bytes/vector |
|---|---|---|---|---|---|
Copy one result into each row. The existing index’s build time can stay blank. Saved bytes per vector is file size divided by the number of indexed vectors. Use total saved bytes for the size cutoff and the full precision values when ranking rows.
Reject any row below the recall floor or above either the latency or size ceiling. Choose the smallest passing index. If two rows use the same number of bytes, choose the one with lower p99.
If no row passes and an index fits the size limit, check ef_construction separately. Pick a candidate M whose recall falls short at the allowed p99. Keep that M and the rest of the setup fixed, set higher_construction_ef above the shared value, then repeat the search sweep on the new build. A higher construction ef can improve graph quality and increase build time. hnswlib parameter notes
# Set candidate_m and higher_construction_ef before running this cell.
check_rows = build_and_sweep(candidate_m, higher_construction_ef)
for row in check_rows:
print(row)
rows.extend(check_rows)
print("Selected:", choose(rows))
If every index is too large, extend the sweep toward smaller M values. If neither sweep yields a passing pair, report which limit each candidate missed and keep the rollout on hold while you revisit the limits or the index design.
Caveats
- Saved bytes measure the serialized index. Check process RAM under representative load if you have a memory cap.
- Recompute exact top-k when the corpus, distance, preprocessing or query set changes.
- Reapply the chosen search
efafter loading a saved hnswlib index. hnswlib Python bindings
Evidence and limits. The Python workflow follows the hnswlib upstream master bindings and exact-recall example. The workflow was not run.
Related across the network
- LangChain Building Blocks: Chains, Tools and Agent Control — langchainguide.com
- LangChain RAG Pipeline: Setup to First Answer — langchainguide.com
- LangChain vs LangGraph vs LlamaIndex Compared — langchainguide.com
- Qdrant vs Milvus vs Pinecone: Vector DB Comparison — ragstackguide.com
- RAG Chunking Strategy: Picking Chunk Size and Overlap — ragstackguide.com