use std::cmp::Ordering;
use crate::error::{VectorError, VectorResult};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Metric {
Cosine,
Dot,
Euclidean,
}
impl Metric {
fn score(&self, a: &[f32], b: &[f32]) -> f32 {
match self {
Metric::Cosine => {
let (na, nb) = (norm(a), norm(b));
if na == 0.0 || nb == 0.0 {
0.0
} else {
dot(a, b) / (na * nb)
}
}
Metric::Dot => dot(a, b),
Metric::Euclidean => -l2(a, b),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Match {
pub id: String,
pub score: f32,
}
struct Entry {
id: String,
vector: Vec<f32>,
}
pub struct VectorIndex {
dim: usize,
metric: Metric,
entries: Vec<Entry>,
}
impl VectorIndex {
pub fn new(dim: usize, metric: Metric) -> Self {
Self {
dim,
metric,
entries: Vec::new(),
}
}
pub fn dim(&self) -> usize {
self.dim
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn insert(&mut self, id: impl Into<String>, vector: Vec<f32>) -> VectorResult<()> {
if vector.len() != self.dim {
return Err(VectorError::DimMismatch {
expected: self.dim,
got: vector.len(),
});
}
let id = id.into();
if let Some(existing) = self.entries.iter_mut().find(|e| e.id == id) {
existing.vector = vector;
} else {
self.entries.push(Entry { id, vector });
}
Ok(())
}
pub fn remove(&mut self, id: &str) -> bool {
let before = self.entries.len();
self.entries.retain(|e| e.id != id);
self.entries.len() != before
}
pub fn search(&self, query: &[f32], k: usize) -> VectorResult<Vec<Match>> {
if query.len() != self.dim {
return Err(VectorError::DimMismatch {
expected: self.dim,
got: query.len(),
});
}
let mut scored: Vec<Match> = self
.entries
.iter()
.map(|e| Match {
id: e.id.clone(),
score: self.metric.score(query, &e.vector),
})
.collect();
scored.sort_by(|a, b| {
b.score
.partial_cmp(&a.score)
.unwrap_or(Ordering::Equal)
.then_with(|| a.id.cmp(&b.id))
});
scored.truncate(k);
Ok(scored)
}
}
fn dot(a: &[f32], b: &[f32]) -> f32 {
a.iter().zip(b).map(|(x, y)| x * y).sum()
}
fn norm(a: &[f32]) -> f32 {
dot(a, a).sqrt()
}
fn l2(a: &[f32], b: &[f32]) -> f32 {
a.iter()
.zip(b)
.map(|(x, y)| {
let d = x - y;
d * d
})
.sum::<f32>()
.sqrt()
}