Struct Index

Source
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

Source

pub fn new(options: &IndexOptions) -> Result<Self, Exception>

Source

pub fn expansion_add(self: &Index) -> usize

Retrieves the expansion value used during index creation.

Retrieves the expansion value used during search.

Source

pub fn change_expansion_add(self: &Index, n: usize)

Updates the expansion value used during index creation. Rarely used.

Updates the expansion value used during search operations.

Source

pub fn change_metric_kind(self: &Index, metric: MetricKind)

Changes the metric kind used to calculate the distance between vectors.

Source

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.

Source

pub fn hardware_acceleration(&self) -> String

Retrieves the hardware acceleration information.

Source

pub fn search<T: VectorType>( self: &Index, query: &[T], count: usize, ) -> Result<Matches, Exception>

Performs k-Approximate Nearest Neighbors (kANN) Search for closest vectors to the provided query.

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

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.

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 a Key and returns true if the corresponding vector should be included in the search results, or false otherwise.
§Returns

A Result containing the matches found.

Source

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

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

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

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

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

pub fn dimensions(self: &Index) -> usize

Retrieves the number of dimensions in the vectors indexed.

Source

pub fn connectivity(self: &Index) -> usize

Retrieves the connectivity parameter that limits connections-per-node in the graph.

Source

pub fn size(self: &Index) -> usize

Retrieves the current number of vectors in the index.

Source

pub fn capacity(self: &Index) -> usize

Retrieves the total capacity of the index, including reserved space.

Source

pub fn serialized_length(self: &Index) -> usize

Reports expected file size after serialization.

Source

pub fn remove(self: &Index, key: Key) -> Result<usize, Exception>

Removes the vector associated with the given key from the index.

§Arguments
  • key - The key of the vector to be removed.
§Returns

true if the vector is successfully removed, false otherwise.

Source

pub fn rename(self: &Index, from: Key, to: Key) -> Result<usize, Exception>

Renames the vector under a specific key.

§Arguments
  • from - The key of the vector to be renamed.
  • to - The new name.
§Returns

true if the vector is renamed, false otherwise.

Source

pub fn contains(self: &Index, key: Key) -> bool

Checks if the index contains a vector with a specified key.

§Arguments
  • key - The key to be checked.
§Returns

true if the index contains the vector with the given key, false otherwise.

Source

pub fn count(self: &Index, key: Key) -> usize

Count the count of vectors with the same specified key.

§Arguments
  • key - The key to be checked.
§Returns

Number of vectors found.

Source

pub fn save(self: &Index, path: &str) -> Result<(), Exception>

Saves the index to a specified file.

§Arguments
  • path - The file path where the index will be saved.
Source

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

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

pub fn reset(self: &Index) -> Result<(), Exception>

Erases all members from the index, closes files, and returns RAM to OS.

Source

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

Source

pub fn save_to_buffer(self: &Index, buffer: &mut [u8]) -> Result<(), Exception>

Saves the index to a specified file.

§Arguments
  • buffer - The buffer where the index will be saved.
Source

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

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.

Trait Implementations§

Source§

impl Drop for Index

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Send for Index

Source§

impl Sync for Index

Auto Trait Implementations§

§

impl Freeze for Index

§

impl !RefUnwindSafe for Index

§

impl Unpin for Index

§

impl !UnwindSafe for Index

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.