Approximate and exact nearest-neighbour search in Rust, with Python bindings.
HNSW is the default. Behind feature flags sit compression families (IVF-PQ, IVF-AVQ, RaBitQ), graph builders (Vamana, DiskANN), the NSW line (NSG, NSW, SNG), random-projection trees, ball and k-d trees, LSH, and binary or 4-bit codes.
The k-d tree and ball tree prune an exact search over normalized vectors. HNSW
searches a graph. Even at ef >= n, a nearest neighbor can be unreachable
from the search entry point. For ground truth, scan the corpus under the same
metric. The full-width HNSW example
compares both paths on 14 points.
Two paths cover what plain HNSW cannot. A filtered graph answers predicate queries without leaving the graph, and an in-place index takes updates without a rebuild.
One protocol measures all of them at the same sizes, so comparisons are between families rather than between benchmarks.
With Rust 1.94 or newer, create a binary crate:
cargo new vicinity-demo
cd vicinity-demoAdd vicinity to the existing [dependencies] table in Cargo.toml:
[dependencies]
vicinity = "0.13.0"Save this in src/main.rs and run cargo run:
use vicinity::hnsw::HNSWIndex;
fn main() -> vicinity::Result<()> {
let mut index = HNSWIndex::builder(2)
.ef_search(50)
.auto_normalize(true)
.build()?;
index.add_slice(7, &[1.0, 0.0])?;
index.add_slice(8, &[0.8, 0.2])?;
index.add_slice(9, &[0.0, 1.0])?;
index.build()?;
let results = index.search(&[1.0, 0.0], 2, 50)?;
for (id, distance) in results {
println!("{id}: {distance:.4}");
}
Ok(())
}7: 0.0000
8: 0.0299
Results carry the IDs you supplied and the distance; lower is closer.
distance::DistanceMetric selects L2, angular or inner product. Cosine assumes
unit-norm vectors unless you set auto_normalize(true). The
examples guide includes runnable search, recall and
persistence examples.
Search within a collection. The filtered neighbors example
uses FilteredGraphIndex::search_filtered with an integer metadata predicate.
Run this command from the repository root.
cargo run --release --example filtered_neighbors --features filtered_graphThe two nearest unfiltered documents belong to collection 1. Collection 2 has
three equidistant documents. Asking for two returns [10, 50], and asking
for five returns [10, 50, 90]. Collection 3 has no matches and returns [].
The filtered graph selects a beam or an exact scan of the matching IDs based on
selectivity. A beam with too few matches falls back to the scan. HNSW's
search_acorn uses a different strategy, expanding second-hop neighbors
during traversal.
On 20k random points at 20% selectivity (one point in five passes the predicate), recall@10 is 1.000 for a pre-filtered exact scan (91 µs), 1.000 for post-filtering an HNSW beam (602 µs), 1.000 through the filtered graph and 0.583 for the ACORN-style two-hop walk (2.1 ms).
The gap opens at the other end. At 0.1% selectivity post-filtering collapses to
0.158 recall while the inverted-list path still returns 1.000. Both tables
print in tests/filtered_recall/,
which writes no rows; the test output is the record.
Updates do not force a rebuild. InPlaceIndex inserts and deletes in place;
HNSWIndex::delete leaves tombstones that are excluded from results and repaired
on demand.
A tombstone stays reachable but never takes one of the ef result slots, so a
deleted point cannot displace a live one
(src/hnsw/search.rs). With 10% of a 5k index deleted and
50 queries scored against exact top-10 over the live ids, recall@10 is 0.788
at ef=10, 0.970 at ef=32, 0.998 at ef=64 and 1.000 at ef=128
(test). No row carries an update rate yet; churn is on
the atlas's list of what has no plot. tests/prop_deletion/
adds the property guard: no deleted id is returned, and recall stays above 0.5
after deleting 10% to 39% of a small index.
It reads from disk if you want. diskann::DiskANNSearcher::load queries
graph.index and vectors.bin through a block cache instead of holding the
index in the heap. At 1M points that costs 2.1× to 3.3× the resident p50
(rows) at an 81.1% cache hit rate
(storage audit).
examples/large_scale.rs, 16-core aarch64, macOS, 2026-11-01. Corpus generated
to disk and memory-mapped, ground truth exact over 500 sampled queries, all rows
committed under benchmarks/.
| n | domain | ef | recall@10 | p50 | build | index on disk | peak RSS | rows |
|---|---|---|---|---|---|---|---|---|
| 100k | clustered | 200 | 0.991 | 303 µs | 5.6 s | 46 MiB | 246 MiB | 100k.jsonl |
| 1M | clustered | 200 | 0.807 | 440 µs | 109 s | 470 MiB | 2.0 GiB | 1m-clustered.jsonl |
| 1M | uniform | 200 | 0.294 | 922 µs | 164 s | 470 MiB | 2.0 GiB | 1m-uniform.jsonl |
| 3M | uniform | 6400 | 0.926 | 16.4 ms | 353 s | 1.4 GiB | 5.8 GiB | 3m-uniform.jsonl |
Distance counts are in benchmarks/large-scale-100k-dists.jsonl:
1411 / 2268 / 3442 / 5782 at ef 50 / 100 / 200 / 800 on 100k clustered.
Each row above is one tier: a corpus size generated by the same harness at
d=96, queried with the same 500 sampled queries and scored against its own
exact top-10 ground truth. A tier is a different problem, not a longer run of the
same one. The generator, the dimension, the metric and the protocol are fixed;
only n changes, so a difference between rows is a property of scale rather than
of a different test. That is also why a tier number cannot be extrapolated: the
same ef=200 reads 0.981 at 10k and 0.294 at 1M (see Limits), and quoting one
tier as if it held for another is the single most common way to misread this
table. Rows for 10M, 100M and 1B are estimates with their basis stated in
benchmarks/README.md, not measurements.
Full-corpus GloVe-100/200 and GloVe-25 numbers, with parameters and repeat spread, are in benchmark results.
| at d=96, m=16 | per point |
|---|---|
| vectors, f32 | 384 B |
| layer-0 adjacency, 32 neighbours | ~136 B |
| ids, reverse map, level | ~17 B |
| measured resident at 1M | 1.26 KiB |
| serialized at 1M | 0.48 KiB |
| measured build peak at 1M | ~2.1 KiB |
The 537 B above is the layout, not the bill. Resident is 2.6× serialized because every node in every layer gets 32 inline neighbour slots and only the few percent of nodes above layer 0 can fill them; the storage audit puts that slack at ~60% of resident memory and ranks a sparse upper-layer layout first.
Two consequences. First, the build is in memory: there is no out-of-core construction, so a 100M index needs roughly 200 GiB of RAM at this peak. DiskANN and SPANN solve that by keeping compressed vectors in RAM and the graph on SSD, and by building the graph in shards; neither path is implemented here. Second, the build peak is not all data: a 1M build costs ~2.1 KiB/point at its peak, and the reorder that permutes the index for locality used to account for ~0.5 KiB of that by copying the corpus. It permutes in place now, which is a transient either way, not a requirement.
One protocol covers every family: exact top-10 ground truth computed before any
index is built, 500 sampled queries on the large-scale tiers, one query at a time
on one thread, and each run committed as a JSONL row under
benchmarks/ or docs/*.jsonl. Every committed row has a
figure: twenty-four families at 10k on uniform and clustered
data, with recall against ef_search and build and memory against the best
recall that family reaches. Distance counts are at 100k; the measured tiers are
100k, 1M and 3M, with index cost plotted against n. Storage appears as resident
against file-backed DiskANN. Three public sets are measured (GloVe-25, SIFT-128,
GIST-960), alongside seed variance and a metric-coverage heatmap.
Three caveats apply before any of it is quoted. Equal ef is not equal recall:
0.981 at 10k and 0.294 at 1M are the same knob. QPS is host-sensitive and
single-threaded: one exact scan here measured 8.6 ms to 26.8 ms an hour apart, so
quote latency with its host. And a row measures one storage mode: resident and
file-backed DiskANN differ by 2.1× to 3.3×, so a row is not the family.
Four terms carry most of the numbers. Recall@10 is the mean fraction of the
true ten nearest neighbours that a query returns, where the truth is an exact
scan of the same corpus. ef_search is the beam width: how many candidates
the walk keeps live, which is the knob that trades latency for recall. It is an
absolute count, not a fraction of n, which is why the same value means
different things at different tiers. A family is one index implementation
(hnsw, ivf_pq, lsh), not a category. A storage mode is where that
family answered from, the heap or the file cache, and the two are separate rows.
Atlas · Storage audit · Full results · Ratchet
Recall is not tier-invariant, and this is the number most likely to be quoted
wrong. On uniform random data at ef=200, recall@10 is
0.981 at 10k,
0.705 at 100k and
0.294 at 1M. The recall is
recoverable: ef=4800 reaches 0.973 at 1M. But at 1M that is 1.45× slower
than the exact scan it is meant to replace. Uniform data in 96 dimensions is
close to the worst case; clustered data holds
0.991 →
0.807 over the same range.
One figure shows the uniform
tiers on one axis.
DiskANN, several tree and quantisation families are experimental: they are measured on the same protocol but their persistence and update paths are not covered to the same depth. The Python wheel exposes HNSW only; IVF-PQ bindings exist in the repository and stay out of the wheel until their persistence contract settles. No GPU path: graph traversal does not port without a second, CAGRA-shaped index.
The package is pyvicinity because vicinity on PyPI is an unrelated project.
pip install pyvicinityimport numpy as np
from pyvicinity import DistanceMetric, HNSWIndex
vectors = np.array([[1.0, 0.0], [0.8, 0.2], [0.0, 1.0]], dtype=np.float32)
index = HNSWIndex(dim=2, metric=DistanceMetric.Cosine, auto_normalize=True, seed=42)
index.add_items(vectors)
index.build()
ids, distances = index.search(vectors[0], k=2)
print(ids.tolist())[0, 1]
examples/python/02_batch_and_recall.py
shows batch search and recall measurement with the published wheel.
To try the IVF-PQ adapter alongside HNSW, clone this repository and run the harness example from its root with uv and Rust 1.94 or newer:
uv run examples/python/03_ann_benchmarks_harness.pyThe first run builds the extension from the checkout. Each adapter prints a
batch shape of (50, 10) for 50 queries requesting 10 neighbors each.
Features are the build contract: an algorithm family you do not enable is not
compiled. --all-features is for comparison work, not for a shipped profile.
| Use case | Features | Adds |
|---|---|---|
| Minimal | --no-default-features |
smallvec, rand, thiserror |
| HNSW | (default) | hnsw, SIMD distance kernels from innr |
| JSON snapshots | hnsw,serde |
save_to_file / load_from_file |
| Binary segments | persistence |
postcard + durability; restart support, generation publication is separate |
| Segmented mutable store | store |
segstore, persistence, HNSW |
| IVF-PQ / OPQ | ivf_pq |
clump, nalgebra |
| Parallel batch search | parallel |
rayon |
| Python | python |
PyO3 abi3-py310, NumPy, HNSW, IVF-PQ, persistence |
| Large-scale harness | large-scale |
memmap2; the example maps files, the library never does |
Where each path lives:
| Need | Use | Feature |
|---|---|---|
| Dense vectors in memory | HNSWIndex |
hnsw |
| Lower memory, recall tradeoff | IVFPQIndex |
ivf_pq |
| Updates without rebuild | InPlaceIndex |
hnsw |
| Query from disk | DiskANNSearcher |
diskann |
| Filtered search | search_acorn, search_filtered |
hnsw, filtered_graph |
Other families and their status are in the algorithm catalogue.
Latest release: 0.12.0 (2026-11-02, crates.io). MSRV 1.94. The crate's own code
is #![forbid(unsafe_code)]; dependencies including Pulp and the benchmark
allocator are not, so this is not a transitive guarantee.
User guide · API · Benchmarks · Algorithms · Datasets · References · Research frontier
MIT OR Apache-2.0