# hnswlib

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

- Category: Retrieval & Knowledge (RAG) / Vector Databases
- Language: C++
- Licence: Apache-2.0
- Repository: https://github.com/nmslib/hnswlib
- Canonical page: https://ai-tldr.dev/tools/hnswlib/

## In short

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.

1. Install

   Install the package from PyPI.

```bash
pip install hnswlib
```

2. 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.

```python
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)
```

3. 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.

```python
p.set_ef(50)
```

## 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
