█

AI/TLDR

Buy me a coffee
Buy me a coffee

hnswlib

Fast approximate nearest-neighbor search with the HNSW graph, in-process for C++ and Python

Vector DatabasesOpen source
Language
C++
License
Apache-2.0
$pip install hnswlib
IN SHORT

What is hnswlib?

hnswlib is a header-only C++ library, with Python bindings, that implements the HNSW (Hierarchical Navigable Small World) graph algorithm for approximate nearest-neighbor search. It sits in the Vector Databases category of the Retrieval & Knowledge (RAG) tools and is open-source, written in C++ and licensed Apache-2.0. To get started: install.

Overview

hnswlib is a header-only C++ library, with Python bindings, that implements the HNSW (Hierarchical Navigable Small World) graph algorithm for approximate nearest-neighbor search. You give it a set of vectors and it returns the closest matches to a query vector, trading a small amount of accuracy for much faster lookups than an exact brute-force scan.

It runs inside your own process rather than as a separate database server, which makes it a fit for the embedded / in-process category of vector search. The Python index is picklable and can be saved to and loaded from disk, so it suits projects that need similarity search without standing up extra infrastructure.

It is aimed at developers building features like semantic search, retrieval for RAG pipelines, recommendations, or deduplication. The library supports incremental index construction, element updates, and deletions, and has no dependencies beyond C++11.

What it does

  • Header-only C++11 with no extra dependencies, plus Python bindings (community-maintained Java and R interfaces also exist)
  • Implements the HNSW graph for approximate nearest-neighbor search with tunable speed/accuracy via M, ef_construction, and ef
  • Incremental index construction: add, update, and delete elements after the index is built
  • Supports squared L2 ('l2'), inner product ('ip'), and cosine ('cosine') distances, plus custom distances in C++
  • Multi-threaded add_items and knn_query, and a picklable Python index that can be saved and reloaded
  • Can replace elements marked as deleted with new ones to keep the index size bounded

Getting started

Install the Python bindings with pip, then build an index, add your vectors, and query for nearest neighbors.

Install

Install the package from PyPI.

bashbash
pip install hnswlib

Build an index and query it

Create an Index for your vector dimension and distance space, initialize it, add your vectors with integer ids, then run a k-NN query.

pythonpython
import hnswlib
import numpy as np

dim = 128
num_elements = 10000

# Generating sample data
data = np.float32(np.random.random((num_elements, dim)))
ids = np.arange(num_elements)

# Declaring index
p = hnswlib.Index(space = 'l2', dim = dim)

# Initializing index
p.init_index(max_elements = num_elements, ef_construction = 200, M = 16)

# Element insertion
p.add_items(data, ids)

# Query dataset
labels, distances = p.knn_query(data, k = 1)

Tune query accuracy

Set ef at query time to trade speed for recall; it must be at least k. Note that ef is not saved with the index, so set it again after loading.

pythonpython
p.set_ef(50)

Commands and code are distilled from the project's own documentation — always check the official repo for the latest.

When to use it

  • Add semantic search or RAG retrieval to an app without running a separate vector database
  • Find nearest neighbors over text or image embeddings in a Python service
  • Build recommendation or deduplication features that match similar items by vector distance
  • Embed approximate nearest-neighbor search directly into a C++ application with no dependencies

How hnswlib compares

hnswlib alongside other open-source vector databases tools AI/TLDR tracks, ranked by GitHub stars.

ToolStarsWhat it does
Supabase★ 116kManaged Postgres backend whose Vector toolkit (pgvector) stores, indexes, and queries embeddings next to transactional data.
Redis Cloud★ 77.8kFully-managed Redis with built-in vector search, offering low-latency similarity and hybrid queries over any embeddings.
Milvus★ 46.8kA distributed vector database for storing and searching billions of embeddings at scale, with multiple index types and Kubernetes-native deployment.
FAISS★ 42kA library from Meta for efficient similarity search and clustering of dense vectors, with both exact and approximate indexes.
Qdrant★ 35.8kA Rust-based vector search engine that stores embeddings with rich payload filtering for semantic search and recommendation systems.
Chroma★ 29.8kA developer-focused vector database designed for quickly building retrieval and RAG features with a simple Python and JavaScript API.
pgvector★ 23.9kA PostgreSQL extension that adds a vector data type and similarity search so you can store and query embeddings inside an existing Postgres database.
hnswlib★ 5.4kFast approximate nearest-neighbor search with the HNSW graph, in-process for C++ and Python