pub struct Index { /* private fields */ }
Expand description
Approximate Nearest Neighbors search index for dense vectors.
The Index
struct provides an abstraction over a dense vector space, allowing
for efficient addition, search, and management of high-dimensional vectors.
It supports various distance metrics and vector types through generic interfaces.
§Examples
Basic usage:
use usearch::{Index, IndexOptions, MetricKind, ScalarKind};
let mut options = IndexOptions::default();
options.dimensions = 4; // Set the number of dimensions for vectors
options.metric = MetricKind::Cos; // Use cosine similarity for distance measurement
options.quantization = ScalarKind::F32; // Use 32-bit floating point numbers
let index = Index::new(&options).expect("Failed to create index.");
index.reserve(1000).expect("Failed to reserve capacity.");
// Add vectors to the index
let vector1: Vec<f32> = vec![0.0, 1.0, 0.0, 1.0];
let vector2: Vec<f32> = vec![1.0, 0.0, 1.0, 0.0];
index.add(1, &vector1).expect("Failed to add vector1.");
index.add(2, &vector2).expect("Failed to add vector2.");
// Search for the nearest neighbors to a query vector
let query: Vec<f32> = vec![0.5, 0.5, 0.5, 0.5];
let results = index.search(&query, 5).expect("Search failed.");
for (key, distance) in results.keys.iter().zip(results.distances.iter()) {
println!("Key: {}, Distance: {}", key, distance);
}
For more examples, including how to add vectors to the index and perform searches, refer to the individual method documentation.
Implementations§
Source§impl Index
impl Index
pub fn new(options: &IndexOptions) -> Result<Self, Exception>
Sourcepub fn expansion_add(self: &Index) -> usize
pub fn expansion_add(self: &Index) -> usize
Retrieves the expansion value used during index creation.
Sourcepub fn expansion_search(self: &Index) -> usize
pub fn expansion_search(self: &Index) -> usize
Retrieves the expansion value used during search.
Sourcepub fn change_expansion_add(self: &Index, n: usize)
pub fn change_expansion_add(self: &Index, n: usize)
Updates the expansion value used during index creation. Rarely used.
Sourcepub fn change_expansion_search(self: &Index, n: usize)
pub fn change_expansion_search(self: &Index, n: usize)
Updates the expansion value used during search operations.
Sourcepub fn change_metric_kind(self: &Index, metric: MetricKind)
pub fn change_metric_kind(self: &Index, metric: MetricKind)
Changes the metric kind used to calculate the distance between vectors.
Sourcepub fn change_metric<T: VectorType>(
self: &mut Index,
metric: Box<dyn Fn(*const T, *const T) -> Distance + Send + Sync>,
)
pub fn change_metric<T: VectorType>( self: &mut Index, metric: Box<dyn Fn(*const T, *const T) -> Distance + Send + Sync>, )
Overrides the metric function used to calculate the distance between vectors.
Sourcepub fn hardware_acceleration(&self) -> String
pub fn hardware_acceleration(&self) -> String
Retrieves the hardware acceleration information.
Sourcepub fn search<T: VectorType>(
self: &Index,
query: &[T],
count: usize,
) -> Result<Matches, Exception>
pub fn search<T: VectorType>( self: &Index, query: &[T], count: usize, ) -> Result<Matches, Exception>
Sourcepub fn exact_search<T: VectorType>(
self: &Index,
query: &[T],
count: usize,
) -> Result<Matches, Exception>
pub fn exact_search<T: VectorType>( self: &Index, query: &[T], count: usize, ) -> Result<Matches, Exception>
Performs exact (brute force) Nearest Neighbors Search for closest vectors to the provided query. This search checks all vectors in the index, guaranteeing to find the true nearest neighbors, but may be slower for large indices.
§Arguments
query
- A slice containing the query vector data.count
- The maximum number of neighbors to search for.
§Returns
A Result
containing the matches found.
Sourcepub fn filtered_search<T: VectorType, F>(
self: &Index,
query: &[T],
count: usize,
filter: F,
) -> Result<Matches, Exception>
pub fn filtered_search<T: VectorType, F>( self: &Index, query: &[T], count: usize, filter: F, ) -> Result<Matches, Exception>
Performs k-Approximate Nearest Neighbors (kANN) Search for closest vectors to the provided query satisfying a custom filter function.
§Arguments
query
- A slice containing the query vector data.count
- The maximum number of neighbors to search for.filter
- A closure that takes aKey
and returnstrue
if the corresponding vector should be included in the search results, orfalse
otherwise.
§Returns
A Result
containing the matches found.
Sourcepub fn add<T: VectorType>(
self: &Index,
key: Key,
vector: &[T],
) -> Result<(), Exception>
pub fn add<T: VectorType>( self: &Index, key: Key, vector: &[T], ) -> Result<(), Exception>
Adds a vector with a specified key to the index.
§Arguments
key
- The key associated with the vector.vector
- A slice containing the vector data.
Sourcepub fn get<T: VectorType>(
self: &Index,
key: Key,
vector: &mut [T],
) -> Result<usize, Exception>
pub fn get<T: VectorType>( self: &Index, key: Key, vector: &mut [T], ) -> Result<usize, Exception>
Extracts one or more vectors matching the specified key.
The vector
slice must be a multiple of the number of dimensions in the index.
After the execution, return the number X
of vectors found.
The vector slice’s first X * dimensions
elements will be filled.
If you are a novice user, consider export
.
§Arguments
key
- The key associated with the vector.vector
- A slice containing the vector data.
Sourcepub fn export<T: VectorType + Default + Clone>(
self: &Index,
key: Key,
vector: &mut Vec<T>,
) -> Result<usize, Exception>
pub fn export<T: VectorType + Default + Clone>( self: &Index, key: Key, vector: &mut Vec<T>, ) -> Result<usize, Exception>
Extracts one or more vectors matching specified key into supplied resizable vector.
The vector
is resized to a multiple of the number of dimensions in the index.
§Arguments
key
- The key associated with the vector.vector
- A mutable vector containing the vector data.
Sourcepub fn reserve(self: &Index, capacity: usize) -> Result<(), Exception>
pub fn reserve(self: &Index, capacity: usize) -> Result<(), Exception>
Reserves memory for a specified number of incoming vectors.
§Arguments
capacity
- The desired total capacity, including the current size.
Sourcepub fn reserve_capacity_and_threads(
self: &Index,
capacity: usize,
threads: usize,
) -> Result<(), Exception>
pub fn reserve_capacity_and_threads( self: &Index, capacity: usize, threads: usize, ) -> Result<(), Exception>
Reserves memory for a specified number of incoming vectors & active threads.
§Arguments
capacity
- The desired total capacity, including the current size.threads
- The number of threads to use for the operation.
Sourcepub fn dimensions(self: &Index) -> usize
pub fn dimensions(self: &Index) -> usize
Retrieves the number of dimensions in the vectors indexed.
Sourcepub fn connectivity(self: &Index) -> usize
pub fn connectivity(self: &Index) -> usize
Retrieves the connectivity parameter that limits connections-per-node in the graph.
Sourcepub fn capacity(self: &Index) -> usize
pub fn capacity(self: &Index) -> usize
Retrieves the total capacity of the index, including reserved space.
Sourcepub fn serialized_length(self: &Index) -> usize
pub fn serialized_length(self: &Index) -> usize
Reports expected file size after serialization.
Sourcepub fn load(self: &Index, path: &str) -> Result<(), Exception>
pub fn load(self: &Index, path: &str) -> Result<(), Exception>
Loads the index from a specified file.
§Arguments
path
- The file path from where the index will be loaded.
Sourcepub fn view(self: &Index, path: &str) -> Result<(), Exception>
pub fn view(self: &Index, path: &str) -> Result<(), Exception>
Creates a view of the index from a file without loading it into memory.
§Arguments
path
- The file path from where the view will be created.
Sourcepub fn reset(self: &Index) -> Result<(), Exception>
pub fn reset(self: &Index) -> Result<(), Exception>
Erases all members from the index, closes files, and returns RAM to OS.
Sourcepub fn memory_usage(self: &Index) -> usize
pub fn memory_usage(self: &Index) -> usize
A relatively accurate lower bound on the amount of memory consumed by the system. In practice, its error will be below 10%.
Sourcepub fn load_from_buffer(self: &Index, buffer: &[u8]) -> Result<(), Exception>
pub fn load_from_buffer(self: &Index, buffer: &[u8]) -> Result<(), Exception>
Loads the index from a specified file.
§Arguments
buffer
- The buffer from where the index will be loaded.
Sourcepub unsafe fn view_from_buffer(
self: &Index,
buffer: &[u8],
) -> Result<(), Exception>
pub unsafe fn view_from_buffer( self: &Index, buffer: &[u8], ) -> Result<(), Exception>
Creates a view of the index from a file without loading it into memory.
§Arguments
buffer
- The buffer from where the view will be created.
§Safety
This function is marked as unsafe
because it stores a pointer to the input buffer.
The caller must ensure that the buffer outlives the index and is not dropped
or modified for the duration of the index’s use. Dereferencing a pointer to a
temporary buffer after it has been dropped can lead to undefined behavior,
which violates Rust’s memory safety guarantees.
Example of misuse:
let index: usearch::Index = usearch::new_index(&usearch::IndexOptions::default()).unwrap();
let temporary = vec![0u8; 100];
index.view_from_buffer(&temporary);
std::mem::drop(temporary);
let query = vec![0.0; 256];
let results = index.search(&query, 5).unwrap();
The above example would result in use-after-free and undefined behavior.