pub enum DistanceMetric {
Cosine,
Euclidean,
DotProduct,
}Expand description
Distance metric for similarity search.
Determines how vector similarity is computed. All metrics return lower values for more similar vectors.
§Choosing a Metric
- Cosine: Best for text embeddings where magnitude doesn’t matter. Measures the angle between vectors. Range: [0, 2].
- Euclidean: Best for spatial data where absolute positions matter. Measures straight-line distance. Range: [0, ∞).
- DotProduct: Best for pre-normalized vectors or when magnitude should influence similarity. Range: (-∞, ∞), negated so lower = more similar.
§Examples
use synadb::distance::DistanceMetric;
// Identical vectors have distance 0 for all metrics
let v = vec![1.0f32, 2.0, 3.0];
assert!(DistanceMetric::Cosine.distance(&v, &v) < 1e-6);
assert!(DistanceMetric::Euclidean.distance(&v, &v) < 1e-6);Variants§
Cosine
Cosine distance: 1 - cos(θ) where θ is the angle between vectors.
Range: [0, 2] where 0 = identical direction, 1 = orthogonal, 2 = opposite. Invariant to vector magnitude - only measures direction.
Euclidean
Euclidean (L2) distance: sqrt(Σ(a_i - b_i)²).
Range: [0, ∞) where 0 = identical vectors. Sensitive to both direction and magnitude.
DotProduct
Negative dot product: -Σ(a_i * b_i).
Range: (-∞, ∞), negated so lower values indicate higher similarity. For normalized vectors, equivalent to cosine similarity.
Implementations§
Source§impl DistanceMetric
impl DistanceMetric
Sourcepub fn distance(&self, a: &[f32], b: &[f32]) -> f32
pub fn distance(&self, a: &[f32], b: &[f32]) -> f32
Compute distance between two vectors.
Lower values indicate more similar vectors for all metrics.
§Arguments
a- First vectorb- Second vector (must have same length asa)
§Returns
The distance between the vectors according to this metric.
§Panics
Debug builds will panic if vectors have different lengths. Release builds have undefined behavior for mismatched lengths.
§Performance
O(n) where n is the vector dimension. Approximately 1μs for 768-dim vectors.
§Examples
use synadb::distance::DistanceMetric;
let query = vec![0.1f32; 128];
let candidate = vec![0.2f32; 128];
let dist = DistanceMetric::Cosine.distance(&query, &candidate);
println!("Distance: {:.4}", dist);Requirements: 1.4
Trait Implementations§
Source§impl Clone for DistanceMetric
impl Clone for DistanceMetric
Source§fn clone(&self) -> DistanceMetric
fn clone(&self) -> DistanceMetric
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more