- ✅ 10x faster HNSW implementation than FAISS.
- ✅ Simple and extensible single C++11 header library.
- ✅ Trusted by giants like Google and DBs like ClickHouse & DuckDB.
- ✅ SIMD-optimized and user-defined metrics with JIT compilation.
- ✅ Hardware-agnostic
f16
&i8
- half-precision & quarter-precision support. - ✅ View large indexes from disk without loading into RAM.
- ✅ Heterogeneous lookups, renaming/relabeling, and on-the-fly deletions.
- ✅ Binary Tanimoto and Sorensen coefficients for Genomics and Chemistry applications.
- ✅ Space-efficient point-clouds with
uint40_t
, accommodating 4B+ size. - ✅ Compatible with OpenMP and custom "executors" for fine-grained parallelism.
- ✅ Semantic Search and Joins.
- 🔄 Near-real-time clustering and sub-clustering for Tens or Millions of clusters.
Technical Insights and related articles:
- Uses Arm SVE and x86 AVX-512's masked loads to eliminate tail
for
-loops. - Uses Horner's method for polynomial approximations, beating GCC 12 by 119x.
- For every language implements a custom separate binding.
Comparison with FAISS
FAISS is a widely recognized standard for high-performance vector search engines. USearch and FAISS both employ the same HNSW algorithm, but they differ significantly in their design principles. USearch is compact and broadly compatible without sacrificing performance, primarily focusing on user-defined metrics and fewer dependencies.
FAISS | USearch | Improvement | |
---|---|---|---|
Indexing time ⁰ | |||
100 Million 96d f32 , f16 , i8 vectors |
2.6 · 2.6 · 2.6 h | 0.3 · 0.2 · 0.2 h | 9.6 · 10.4 · 10.7 x |
100 Million 1536d f32 , f16 , i8 vectors |
5.0 · 4.1 · 3.8 h | 2.1 · 1.1 · 0.8 h | 2.3 · 3.6 · 4.4 x |
Codebase length ¹ | 84 K SLOC | 3 K SLOC | maintainable |
Supported metrics ² | 9 fixed metrics | any metric | extendible |
Supported languages ³ | C++, Python | 10 languages | portable |
Supported ID types ⁴ | 32-bit, 64-bit | 32-bit, 40-bit, 64-bit | efficient |
Filtering ⁵ | ban-lists | any predicates | composable |
Required dependencies ⁶ | BLAS, OpenMP | - | light-weight |
Bindings ⁷ | SWIG | Native | low-latency |
Python binding size ⁸ | ~ 10 MB | < 1 MB | deployable |
⁰ Tested on Intel Sapphire Rapids, with the simplest inner-product distance, equivalent recall, and memory consumption while also providing far superior search speed. ¹ A shorter codebase of
usearch/
overfaiss/
makes the project easier to maintain and audit. ² User-defined metrics allow you to customize your search for various applications, from GIS to creating custom metrics for composite embeddings from multiple AI models or hybrid full-text and semantic search. ³ With USearch, you can reuse the same preconstructed index in various programming languages. ⁴ The 40-bit integer allows you to store 4B+ vectors without allocating 8 bytes for every neighbor reference in the proximity graph. ⁵ With USearch the index can be combined with arbitrary external containers, like Bloom filters or third-party databases, to filter out irrelevant keys during index traversal. ⁶ Lack of obligatory dependencies makes USearch much more portable. ⁷ Native bindings introduce lower call latencies than more straightforward approaches. ⁸ Lighter bindings make downloads and deployments faster.
Base functionality is identical to FAISS, and the interface must be familiar if you have ever investigated Approximate Nearest Neighbors search:
# pip install usearch
= # Default settings for 3D vectors
= # Can be a matrix for batch operations
# Add one or many vectors in parallel
= # Find 10 nearest neighbors
assert . == 42
assert . <= 0.001
assert # Ensure high tolerance in mixed-precision comparisons
More settings are always available, and the API is designed to be as flexible as possible.
The default storage/quantization level is hardware-dependant for efficiency, but bf16
is recommended for most modern CPUs.
=
Serialization & Serving Index
from Disk
USearch supports multiple forms of serialization:
- Into a file defined with a path.
- Into a stream defined with a callback, serializing or reconstructing incrementally.
- Into a buffer of fixed length or a memory-mapped file that supports random access.
The latter allows you to serve indexes from external memory, enabling you to optimize your server choices for indexing speed and serving costs. This can result in 20x cost reduction on AWS and other public clouds.
=
=
=
Exact vs. Approximate Search
Approximate search methods, such as HNSW, are predominantly used when an exact brute-force search becomes too resource-intensive.
This typically occurs when you have millions of entries in a collection.
For smaller collections, we offer a more direct approach with the search
method.
# Generate 10'000 random vectors with 1024 dimensions
=
=
: =
: =
If you pass the exact=True
argument, the system bypasses indexing altogether and performs a brute-force search through the entire dataset using SIMD-optimized similarity metrics from SimSIMD.
When compared to FAISS's IndexFlatL2
in Google Colab, USearch may offer up to a 20x performance improvement:
faiss.IndexFlatL2
: 55.3 ms.usearch.index.search
: 2.54 ms.
User-Defined Metrics
While most vector search packages concentrate on just two metrics, "Inner Product distance" and "Euclidean distance", USearch allows arbitrary user-defined metrics. This flexibility allows you to customize your search for various applications, from computing geospatial coordinates with the rare Haversine distance to creating custom metrics for composite embeddings from multiple AI models, like joint image-text embeddings. You can use Numba, Cppyy, or PeachPy to define your custom metric even in Python:
=
=
= 0.0
+= *
return 1 -
=
=
Similar effect is even easier to achieve in C, C++, and Rust interfaces. Moreover, unlike older approaches indexing high-dimensional spaces, like KD-Trees and Locality Sensitive Hashing, HNSW doesn't require vectors to be identical in length. They only have to be comparable. So you can apply it in obscure applications, like searching for similar sets or fuzzy text matching, using GZip compression-ratio as a distance function.
Filtering and Predicate Functions
Sometimes you may want to cross-reference search-results against some external database or filter them based on some criteria. In most engines, you'd have to manually perform paging requests, successively filtering the results. In USearch you can simply pass a predicate function to the search method, which will be applied directly during graph traversal. In Rust that would look like this:
let is_odd = ;
let query = vec!;
let results = index.filtered_search.unwrap;
assert!;
Memory Efficiency, Downcasting, and Quantization
Training a quantization model and dimension-reduction is a common approach to accelerate vector search.
Those, however, are only sometimes reliable, can significantly affect the statistical properties of your data, and require regular adjustments if your distribution shifts.
Instead, we have focused on high-precision arithmetic over low-precision downcasted vectors.
The same index, and add
and search
operations will automatically down-cast or up-cast between f64_t
, f32_t
, f16_t
, i8_t
, and single-bit b1x8_t
representations.
You can use the following command to check, if hardware acceleration is enabled:
> sapphire
> ice
In most cases, it's recommended to use half-precision floating-point numbers on modern hardware.
When quantization is enabled, the "get"-like functions won't be able to recover the original data, so you may want to replicate the original vectors elsewhere.
When quantizing to i8_t
integers, note that it's only valid for cosine-like metrics.
As part of the quantization process, the vectors are normalized to unit length and later scaled to [-127, 127] range to occupy the full 8-bit range.
When quantizing to b1x8_t
single-bit representations, note that it's only valid for binary metrics like Jaccard, Hamming, etc.
As part of the quantization process, the scalar components greater than zero are set to true
, and the rest to false
.
Using smaller numeric types will save you RAM needed to store the vectors, but you can also compress the neighbors lists forming our proximity graphs.
By default, 32-bit uint32_t
is used to enumerate those, which is not enough if you need to address over 4 Billion entries.
For such cases we provide a custom uint40_t
type, that will still be 37.5% more space-efficient than the commonly used 8-byte integers, and will scale up to 1 Trillion entries.
Indexes
for Multi-Index Lookups
For larger workloads targeting billions or even trillions of vectors, parallel multi-index lookups become invaluable. Instead of constructing one extensive index, you can build multiple smaller ones and view them together.
=
Clustering
Once the index is constructed, USearch can perform K-Nearest Neighbors Clustering much faster than standalone clustering libraries, like SciPy,
UMap, and tSNE.
Same for dimensionality reduction with PCA.
Essentially, the Index
itself can be seen as a clustering, allowing iterative deepening.
=
# Get the clusters and their sizes
, =
# Use Matplotlib to draw a histogram
# Export a NetworkX graph of the clusters
=
# Get members of a specific cluster
=
# Deepen into that cluster, splitting it into more parts, all the same arguments supported
=
The resulting clustering isn't identical to K-Means or other conventional approaches but serves the same purpose. Alternatively, using Scikit-Learn on a 1 Million point dataset, one may expect queries to take anywhere from minutes to hours, depending on the number of clusters you want to highlight. For 50'000 clusters, the performance difference between USearch and conventional clustering methods may easily reach 100x.
Joins, One-to-One, One-to-Many, and Many-to-Many Mappings
One of the big questions these days is how AI will change the world of databases and data management.
Most databases are still struggling to implement high-quality fuzzy search, and the only kind of joins they know are deterministic.
A join
differs from searching for every entry, requiring a one-to-one mapping banning collisions among separate search results.
Exact Search | Fuzzy Search | Semantic Search ? |
---|---|---|
Exact Join | Fuzzy Join ? | Semantic Join ?? |
Using USearch, one can implement sub-quadratic complexity approximate, fuzzy, and semantic joins. This can be useful in any fuzzy-matching tasks common to Database Management Software.
=
=
: =
Read more in the post: Combinatorial Stable Marriages for Semantic Search 💍
Functionality
By now, the core functionality is supported across all bindings. Broader functionality is ported per request. In some cases, like Batch operations, feature parity is meaningless, as the host language has full multi-threading capabilities and the USearch index structure is concurrent by design, so the users can implement batching/scheduling/load-balancing in the most optimal way for their applications.
C++ 11 | Python 3 | C 99 | Java | JavaScript | Rust | GoLang | Swift | |
---|---|---|---|---|---|---|---|---|
Add, search, remove | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Save, load, view | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
User-defined metrics | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
Batch operations | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
Filter predicates | ✅ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ |
Joins | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
Variable-length vectors | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
4B+ capacities | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
Application Examples
USearch + UForm + UCall = Multimodal Semantic Search
AI has a growing number of applications, but one of the coolest classic ideas is to use it for Semantic Search. One can take an encoder model, like the multi-modal UForm, and a web-programming framework, like UCall, and build a text-to-image search platform in just 20 lines of Python.
=
=
=
=
=
=
=
=
=
=
=
=
return
,
Similar experiences can also be implemented in other languages and on the client side, removing the network latency.
For Swift and iOS, check out the ashvardanian/SwiftSemanticSearch
repository.
A more complete demo with Streamlit is available on GitHub. We have pre-processed some commonly used datasets, cleaned the images, produced the vectors, and pre-built the index.
Dataset | Modalities | Images | Download |
---|---|---|---|
Unsplash | Images & Descriptions | 25 K | HuggingFace / Unum |
Conceptual Captions | Images & Descriptions | 3 M | HuggingFace / Unum |
Arxiv | Titles & Abstracts | 2 M | HuggingFace / Unum |
USearch + RDKit = Molecular Search
Comparing molecule graphs and searching for similar structures is expensive and slow. It can be seen as a special case of the NP-Complete Subgraph Isomorphism problem. Luckily, domain-specific approximate methods exist. The one commonly used in Chemistry is to generate structures from SMILES and later hash them into binary fingerprints. The latter are searchable with binary similarity metrics, like the Tanimoto coefficient. Below is an example using the RDKit package.
=
=
=
=
=
=
=
That method was used to build the "USearch Molecules", one of the largest Chem-Informatics datasets, containing 7 billion small molecules and 28 billion fingerprints.
USearch + POI Coordinates = GIS Applications
Similar to Vector and Molecule search, USearch can be used for Geospatial Information Systems. The Haversine distance is available out of the box, but you can also define more complex relationships, like the Vincenty formula, that accounts for the Earth's oblateness.
# Define the dimension as 2 for latitude and longitude
= 2
# Signature for the custom metric
=
# WGS-84 ellipsoid parameters
= 6378137.0 # major axis in meters
= 1 / 298.257223563 # flattening
= * # minor axis
=
=
, , , = , , ,
, , = - , ,
, , , = , , ,
, = , 100
-= 1
, = ,
=
return 0.0 # Co-incident points
, = * + * * ,
, = * * / , 1 - ** 2
= - 2 * * / # Equatorial line
= / 16 * *
, = + * * ,
break
return # formula failed to converge
= * /
= 1 + / 16384 *
= / 1024 *
= * *
= * *
return / 1000.0 # Distance in kilometers
# Example usage:
=
Integrations & Users
- ClickHouse: C++, docs.
- DuckDB: post.
- Google: UniSim, RetSim paper.
- LanternDB: C++, Rust, docs.
- LangChain: Python and JavaScript.
- Microsoft Semantic Kernel: Python and C#.
- GPTCache: Python.
- Sentence-Transformers: Python docs.
- Pathway: Rust.
Citations