Skip to main content

ares_vector/
collection.rs

1//! Vector collection.
2//!
3//! A collection is a named container for vectors with a specific dimensionality
4//! and distance metric.
5
6use crate::config::HnswConfig;
7use crate::distance::DistanceMetric;
8use crate::error::Result;
9use crate::index::HnswIndex;
10use crate::types::{SearchResult, VectorMetadata};
11use crate::{CollectionStats, HnswParams};
12use std::sync::Arc;
13
14/// A named collection of vectors.
15///
16/// Each collection has:
17/// - A unique name
18/// - Fixed vector dimensions
19/// - A distance metric for similarity calculations
20/// - An HNSW index for fast approximate nearest neighbor search
21pub struct Collection {
22    /// Collection name.
23    name: String,
24    /// Vector dimensions.
25    dimensions: usize,
26    /// Distance metric.
27    metric: DistanceMetric,
28    /// The underlying HNSW index.
29    index: Arc<HnswIndex>,
30    /// HNSW configuration.
31    hnsw_config: HnswConfig,
32}
33
34impl Collection {
35    /// Create a new collection.
36    pub fn new(
37        name: String,
38        dimensions: usize,
39        metric: DistanceMetric,
40        hnsw_config: HnswConfig,
41    ) -> Result<Self> {
42        let index = HnswIndex::new(dimensions, metric, hnsw_config.clone())?;
43
44        Ok(Self {
45            name,
46            dimensions,
47            metric,
48            index: Arc::new(index),
49            hnsw_config,
50        })
51    }
52
53    /// Get the collection name.
54    pub fn name(&self) -> &str {
55        &self.name
56    }
57
58    /// Get the vector dimensions.
59    pub fn dimensions(&self) -> usize {
60        self.dimensions
61    }
62
63    /// Get the distance metric.
64    pub fn metric(&self) -> DistanceMetric {
65        self.metric
66    }
67
68    /// Get the number of vectors in the collection.
69    pub fn len(&self) -> usize {
70        self.index.len()
71    }
72
73    /// Check if the collection is empty.
74    pub fn is_empty(&self) -> bool {
75        self.index.is_empty()
76    }
77
78    /// Insert a vector.
79    pub fn insert(&self, id: &str, vector: &[f32], metadata: Option<VectorMetadata>) -> Result<()> {
80        self.index.insert(id, vector, metadata)
81    }
82
83    /// Insert multiple vectors in batch.
84    pub fn insert_batch<'a, I>(&self, vectors: I) -> Result<usize>
85    where
86        I: IntoIterator<Item = (&'a str, &'a [f32], Option<VectorMetadata>)>,
87    {
88        self.index.insert_batch(vectors)
89    }
90
91    /// Update a vector.
92    pub fn update(&self, id: &str, vector: &[f32], metadata: Option<VectorMetadata>) -> Result<()> {
93        self.index.update(id, vector, metadata)
94    }
95
96    /// Delete a vector.
97    pub fn delete(&self, id: &str) -> Result<bool> {
98        self.index.delete(id)
99    }
100
101    /// Delete multiple vectors.
102    pub fn delete_batch(&self, ids: &[&str]) -> Result<usize> {
103        self.index.delete_batch(ids)
104    }
105
106    /// Search for similar vectors.
107    pub fn search(&self, query: &[f32], limit: usize) -> Result<Vec<SearchResult>> {
108        self.index.search(query, limit)
109    }
110
111    /// Search with a minimum score threshold.
112    pub fn search_with_threshold(
113        &self,
114        query: &[f32],
115        limit: usize,
116        min_score: f32,
117    ) -> Result<Vec<SearchResult>> {
118        self.index.search_with_threshold(query, limit, min_score)
119    }
120
121    /// Get a vector by ID.
122    pub fn get(&self, id: &str) -> Option<(Vec<f32>, Option<VectorMetadata>)> {
123        self.index.get(id)
124    }
125
126    /// Check if a vector exists.
127    pub fn contains(&self, id: &str) -> bool {
128        self.index.contains(id)
129    }
130
131    /// Compact the index.
132    pub fn compact(&self) -> Result<()> {
133        self.index.compact()
134    }
135
136    /// Get collection statistics.
137    pub fn stats(&self) -> CollectionStats {
138        CollectionStats {
139            name: self.name.clone(),
140            vector_count: self.index.len(),
141            dimensions: self.dimensions,
142            metric: self.metric,
143            memory_bytes: self.index.memory_usage(),
144            hnsw_params: HnswParams {
145                m: self.hnsw_config.m,
146                ef_construction: self.hnsw_config.ef_construction,
147                ef_search: self.hnsw_config.ef_search,
148            },
149        }
150    }
151
152    /// Get the HNSW configuration.
153    pub fn hnsw_config(&self) -> &HnswConfig {
154        &self.hnsw_config
155    }
156
157    /// Get a reference to the underlying index.
158    #[allow(dead_code)]
159    pub(crate) fn index(&self) -> &Arc<HnswIndex> {
160        &self.index
161    }
162
163    /// Export all vectors for persistence.
164    ///
165    /// Returns a vector of (id, vector, metadata) tuples.
166    pub fn export_all(&self) -> Vec<(String, Vec<f32>, Option<VectorMetadata>)> {
167        self.index.export_all()
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    fn default_config() -> HnswConfig {
176        HnswConfig::default()
177    }
178
179    #[test]
180    fn test_collection_basic() {
181        let col = Collection::new(
182            "test".to_string(),
183            3,
184            DistanceMetric::Cosine,
185            default_config(),
186        )
187        .unwrap();
188
189        assert_eq!(col.name(), "test");
190        assert_eq!(col.dimensions(), 3);
191        assert_eq!(col.metric(), DistanceMetric::Cosine);
192        assert!(col.is_empty());
193    }
194
195    #[test]
196    fn test_collection_operations() {
197        let col = Collection::new(
198            "test".to_string(),
199            3,
200            DistanceMetric::Cosine,
201            default_config(),
202        )
203        .unwrap();
204
205        col.insert("vec1", &[1.0, 0.0, 0.0], None).unwrap();
206        col.insert("vec2", &[0.0, 1.0, 0.0], None).unwrap();
207
208        assert_eq!(col.len(), 2);
209        assert!(col.contains("vec1"));
210        assert!(col.contains("vec2"));
211        assert!(!col.contains("vec3"));
212
213        let results = col.search(&[1.0, 0.0, 0.0], 10).unwrap();
214        assert!(!results.is_empty());
215
216        col.delete("vec1").unwrap();
217        assert!(!col.contains("vec1"));
218        assert_eq!(col.len(), 1);
219    }
220
221    #[test]
222    fn test_collection_stats() {
223        let col = Collection::new(
224            "test".to_string(),
225            128,
226            DistanceMetric::Euclidean,
227            HnswConfig::accurate(),
228        )
229        .unwrap();
230
231        col.insert("vec1", &vec![0.0; 128], None).unwrap();
232
233        let stats = col.stats();
234        assert_eq!(stats.name, "test");
235        assert_eq!(stats.vector_count, 1);
236        assert_eq!(stats.dimensions, 128);
237        assert_eq!(stats.metric, DistanceMetric::Euclidean);
238        assert!(stats.memory_bytes > 0);
239    }
240}