Registry / vector-search / hnswlib

hnswlib

JSON →
library0.8.0pypypi✓ verified 85d ago

Hnswlib is a lightweight, header-only C++ library with Python bindings designed for fast Approximate Nearest Neighbor (ANN) search. It implements the Hierarchical Navigable Small Worlds (HNSW) algorithm, enabling efficient similarity search in high-dimensional vector spaces. The library supports dynamic updates (insertion and deletion of elements) and various distance metrics like L2, Inner Product, and Cosine similarity. Its current stable release on PyPI is 0.8.0, with version 0.9.0 recently released on GitHub, and it maintains a relatively active release cadence.

pip install hnswlib
INSTALL
IMPORT
SIG · HNSWLIB
H
hnswlib
vector-searchpythonv0.8.0
Install
Import
Disk
Pass rate
0/ 10
Env Coverage0 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v? · pip install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
build_error
glibc
py 3.103.920 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Index
import hnswlib import numpy as np index = hnswlib.Index(space='l2', dim=128)

This quickstart demonstrates how to create an HNSW index, initialize it with parameters, add vector data, perform a k-nearest neighbor query, and then save and load the index. It highlights the importance of re-setting the `ef` parameter after loading the index.

import hnswlib import numpy as np import os # Define data parameters dim = 128 num_elements = 10000 # Generate random data data = np.float32(np.random.random((num_elements, dim))) data_labels = np.arange(num_elements) # Initialize the HNSW index # Possible space options: 'l2', 'ip' (inner product), 'cosine' space_name = 'l2' # Euclidean distance index = hnswlib.Index(space=space_name, dim=dim) # Set index parameters BEFORE adding data # max_elements: current capacity # ef_construction: accuracy vs. construction speed trade-off # M: number of bi-directional links per data point index.init_index(max_elements=num_elements, ef_construction=200, M=16) # Add items to the index index.add_items(data, data_labels) # Set query time accuracy/speed trade-off # Note: This parameter is NOT saved with the index and must be set after loading. index.set_ef(50) # Generate a query vector query_vector = np.float32(np.random.random((1, dim))) # Perform a k-nearest neighbor query k = 5 labels, distances = index.knn_query(query_vector, k=k) print(f"Query vector: {query_vector[0][:5]}...") print(f"Nearest neighbor labels: {labels[0]}") print(f"Distances to neighbors: {distances[0]}") # Example of saving and loading the index index_path = 'my_hnsw_index.bin' index.save_index(index_path) loaded_index = hnswlib.Index(space=space_name, dim=dim) loaded_index.load_index(index_path) loaded_index.set_ef(50) # Re-set ef after loading loaded_labels, loaded_distances = loaded_index.knn_query(query_vector, k=k) print(f"Loaded index nearest neighbor labels: {loaded_labels[0]}") os.remove(index_path)
Debug
Known issues
breakingIndices saved with very old versions (prior to v0.3.4) are not supported and cannot be loaded with newer `hnswlib` versions.
fix
Rebuild indices with a supported `hnswlib` version. Consider exporting data and re-importing if migration is critical.
affects: < 0.3.4
breakingSaving and loading of large pickled indices (greater than 4GB) in versions prior to 0.6.2 could lead to data corruption.
fix
Upgrade to `hnswlib` v0.6.2 or later to prevent corruption of large pickled indices. Rebuild any potentially corrupted indices.
affects: < 0.6.2
breakingIndices built with AVX512 or AVX optimizations (enabled during compilation) in `hnswlib` v0.6.1 and later may not be backwards-compatible with older SSE or non-AVX512 architectures. This can cause issues when moving indices between machines with different CPU capabilities.
fix
Ensure that the `hnswlib` library is compiled and indices are used on machines with compatible CPU architectures and instruction sets. Recompile without specific AVX flags if maximum portability is needed, or rebuild indices on the target architecture.
affects: >= 0.6.1
gotchaThe `ef` parameter, which controls the query-time accuracy/speed trade-off, is *not* saved as part of the index. It must be manually set after loading a saved index.
fix
Always call `index.set_ef(value)` after loading an index to configure the desired query performance.
affects: All versions
breakingIn `hnswlib` v0.8.0, statistic aggregation was removed by default for multi-threaded search to improve speed. Users who relied on this feature might observe changes in behavior or require explicit configuration if it's still needed.
fix
Review multi-threaded search logic; if statistic aggregation was implicitly relied upon, evaluate impact. Check release notes for explicit alternatives if available.
affects: >= 0.8.0
gotchaWhen performing brute-force searches with filters, versions prior to 0.9.0 (currently on GitHub, not yet PyPI stable) contained bugs that could lead to incorrect results or missing normalization checks. Additionally, searching for `k` elements when fewer than `k` are available now explicitly throws an exception.
fix
Upgrade to `hnswlib` v0.9.0 or later once released on PyPI for correct filter behavior and robust error handling when `k` exceeds available elements.
affects: < 0.9.0
Errors
Common errors & fixes
ERROR: Failed building wheel for hnswlib
Hnswlib is a C++ library with Python bindings, requiring a C++ compiler and Python development headers to build from source during `pip install`.
fix
On Linux, install Python development headers and build tools: `sudo apt-get install python3-dev build-essential`. On Windows, install the 'Desktop development with C++' workload from Visual Studio Build Tools. Alternatively, try `pip install hnswlib --only-binary=:all:` to install pre-built wheels, or use `conda install -c conda-forge hnswlib`.
AttributeError: module 'hnswlib' has no attribute 'Index'
This error typically indicates that the `hnswlib` module was imported, but the `Index` class is not accessible, often due to an incomplete, corrupted, or conflicting installation within the Python environment.
fix
Reinstall `hnswlib` in a clean virtual environment: first, `pip uninstall hnswlib`, then `pip install hnswlib`. Ensure no other packages are inadvertently shadowing or conflicting with `hnswlib`.
AttributeError: type object 'hnswlib.Index' has no attribute 'file_handle_count'
This specific error commonly occurs when `hnswlib` is used in conjunction with `chromadb`, often due to version conflicts between the `hnswlib` and `chroma-hnswlib` packages or an issue where one is shadowing the other.
fix
Ensure that only a compatible version of `hnswlib` or `chroma-hnswlib` (if `chromadb` requires it) is installed. A common solution is to uninstall both and let `chromadb` install its required dependency: `pip uninstall hnswlib chromadb chroma-hnswlib` followed by `pip install chromadb`.
Warning: Calling load_index for an already inited index. Old index is being deallocated. (or similar issues where index properties are 0 after load)
When loading an existing index from disk, the `hnswlib.Index` object should be created but not initialized with `init_index()` before calling `load_index()`. Doing so can cause the loaded index to behave unexpectedly, such as showing zero elements or incorrect parameters.
fix
Create a new, uninitialized `hnswlib.Index` object and directly call `load_index()` on it with the path to the saved index file. For example: `new_index = hnswlib.Index(space='l2', dim=128); new_index.load_index('saved_index.bin')`.
RuntimeError: The number of elements exceeds the specified limit
The index was initialized with a `max_elements` parameter, and a subsequent call to `add_items()` attempts to insert more elements than the currently allocated capacity without explicitly resizing the index.
fix
Before adding more elements, dynamically increase the index's capacity using the `resize_index()` method: `index.resize_index(new_size)`, where `new_size` must be greater than the current number of elements plus the new elements to be added.
Upgrade
Version history
0.8.0latest on PyPI · released Dec 3, 2023
Audit
Dependencies
numpyrequiredRequired for handling vector data (NumPy arrays) in Python bindings.
Agent activity
62 hits · last 30 days
node
54
Perplexity
1
OpenAI (training)
1
Resources
hnswlib — pip install hnswlib · libregistry