nmslib/hnswlib

Header-only C++/python library for fast approximate nearest neighbors

What is hnswlib?

hnswlib is a header‑only C++ library that implements the Hierarchical Navigable Small World (HNSW) algorithm for fast approximate nearest‑neighbor (ANN) search. It ships with Python bindings (installable via pip) and optional bindings for Java, R, etc. The library lets you build an index of high‑dimensional vectors, add or delete items incrementally, and query for the k closest vectors with a controllable speed‑accuracy trade‑off.


Why use it?

Feature Benefit
Header‑only, C++11 No external dependencies; just include the headers and compile.
Python API Easy to use from NumPy‑based workflows; the index object is picklable.
Incremental updates Add, delete, or replace vectors after the index is built; deletions are lazy (marked) and can be reclaimed.
Custom distances Supports L2, inner‑product, cosine out‑of‑the‑box; any user‑defined metric can be added in C++.
Multithreaded construction & search Use all CPU cores via num_threads arguments.
Low memory footprint Smaller than the original nmslib HNSW implementation.
No‑exception build option Compile with -fno-exceptions (-DHNSWLIB_ENABLE_EXCEPTIONS=OFF) for environments that forbid C++ exceptions.

Core concepts

  • Space – the distance function ('l2', 'ip' for inner‑product, 'cosine').
  • dim – dimensionality of the vectors.
  • M – maximum number of outgoing links per node in the graph (higher → more accuracy, more memory).
  • ef_construction – controls how much work is spent building the graph (higher → better recall, slower build).
  • ef – query‑time counterpart of ef_construction; larger values give higher recall at the cost of slower queries.

Typical workflow (Python)

import hnswlib, numpy as np

# 1️⃣ Create an empty index
p = hnswlib.Index(space='l2', dim=128)

# 2️⃣ Initialise capacity and construction parameters
p.init_index(max_elements=100_000, M=16, ef_construction=200)

# 3️⃣ Add vectors (NumPy array shape: N×dim)
data = np.random.rand(10_000, 128).astype('float32')
ids   = np.arange(10_000)               # optional integer labels
p.add_items(data, ids)

# 4️⃣ Tune query accuracy
p.set_ef(50)   # ef must be > k

# 5️⃣ Query
labels, distances = p.knn_query(data[:5], k=3)
print(labels, distances)

# 6️⃣ Persist / reload
p.save_index('my_index.bin')
# … later …
q = hnswlib.Index(space='l2', dim=128)
q.load_index('my_index.bin', max_elements=200_000)

The same steps exist in C++ with analogous method names (add_items, knn_query, save_index, …).


Advanced features

  • Filtering – supply a callable filter to knn_query to restrict results to a subset of labels (Python only, slower due to the GIL).
  • Deletion & replacement – mark_deleted(label) hides an element; with allow_replace_deleted=True you can reuse that slot for new data.
  • Epsilon search & multi‑vector queries – available in the C++ API for radius‑based or batch searches.
  • No‑exception API – methods ending in *NoExceptions return a Status object instead of throwing, useful for strict build environments.

When to choose hnswlib

  • You need high‑speed ANN for vectors of moderate to high dimension (e.g., embeddings from language models, image features, recommendation vectors).
  • You want incremental updates without rebuilding the whole index.
  • You prefer a lightweight, dependency‑free solution that works both in C++ and Python.
  • Your workload can tolerate approximate results (recall can be tuned via ef).

Related projects

  • nmslib – a broader library offering many non‑metric spaces; hnswlib can be used as a fast HNSW backend.
  • FAISS – Facebook’s ANN library; includes its own HNSW implementation for coarse quantization.
  • Various language ports (Go, Rust, Java, .NET, CUDA) listed in the README for those needing a non‑Python ecosystem.

Getting started

# From source
git clone https://github.com/nmslib/hnswlib.git
cd hnswlib
pip install .

# Or simply
pip install hnswlib

Run the bundled unit tests to verify the installation:

python -m unittest discover -s tests/python -p "bindings_test*.py"

In short: hnswlib provides a fast, memory‑efficient, and easy‑to‑use implementation of the HNSW ANN algorithm, with full support for incremental updates and a Python interface that fits naturally into modern ML pipelines.

Related

  • Project
  • Project
  • Project
  • Project
  • Project