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(
80        &self,
81        id: &str,
82        vector: &[f32],
83        metadata: Option<VectorMetadata>,
84    ) -> Result<()> {
85        self.index.insert(id, vector, metadata)
86    }
87
88    /// Insert multiple vectors in batch.
89    pub fn insert_batch<'a, I>(&self, vectors: I) -> Result<usize>
90    where
91        I: IntoIterator<Item = (&'a str, &'a [f32], Option<VectorMetadata>)>,
92    {
93        self.index.insert_batch(vectors)
94    }
95
96    /// Update a vector.
97    pub fn update(
98        &self,
99        id: &str,
100        vector: &[f32],
101        metadata: Option<VectorMetadata>,
102    ) -> Result<()> {
103        self.index.update(id, vector, metadata)
104    }
105
106    /// Delete a vector.
107    pub fn delete(&self, id: &str) -> Result<bool> {
108        self.index.delete(id)
109    }
110
111    /// Delete multiple vectors.
112    pub fn delete_batch(&self, ids: &[&str]) -> Result<usize> {
113        self.index.delete_batch(ids)
114    }
115
116    /// Search for similar vectors.
117    pub fn search(&self, query: &[f32], limit: usize) -> Result<Vec<SearchResult>> {
118        self.index.search(query, limit)
119    }
120
121    /// Search with a minimum score threshold.
122    pub fn search_with_threshold(
123        &self,
124        query: &[f32],
125        limit: usize,
126        min_score: f32,
127    ) -> Result<Vec<SearchResult>> {
128        self.index.search_with_threshold(query, limit, min_score)
129    }
130
131    /// Get a vector by ID.
132    pub fn get(&self, id: &str) -> Option<(Vec<f32>, Option<VectorMetadata>)> {
133        self.index.get(id)
134    }
135
136    /// Check if a vector exists.
137    pub fn contains(&self, id: &str) -> bool {
138        self.index.contains(id)
139    }
140
141    /// Compact the index.
142    pub fn compact(&self) -> Result<()> {
143        self.index.compact()
144    }
145
146    /// Get collection statistics.
147    pub fn stats(&self) -> CollectionStats {
148        CollectionStats {
149            name: self.name.clone(),
150            vector_count: self.index.len(),
151            dimensions: self.dimensions,
152            metric: self.metric,
153            memory_bytes: self.index.memory_usage(),
154            hnsw_params: HnswParams {
155                m: self.hnsw_config.m,
156                ef_construction: self.hnsw_config.ef_construction,
157                ef_search: self.hnsw_config.ef_search,
158            },
159        }
160    }
161
162    /// Get the HNSW configuration.
163    pub fn hnsw_config(&self) -> &HnswConfig {
164        &self.hnsw_config
165    }
166
167    /// Get a reference to the underlying index.
168    #[allow(dead_code)]
169    pub(crate) fn index(&self) -> &Arc<HnswIndex> {
170        &self.index
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    fn default_config() -> HnswConfig {
179        HnswConfig::default()
180    }
181
182    #[test]
183    fn test_collection_basic() {
184        let col = Collection::new(
185            "test".to_string(),
186            3,
187            DistanceMetric::Cosine,
188            default_config(),
189        )
190        .unwrap();
191
192        assert_eq!(col.name(), "test");
193        assert_eq!(col.dimensions(), 3);
194        assert_eq!(col.metric(), DistanceMetric::Cosine);
195        assert!(col.is_empty());
196    }
197
198    #[test]
199    fn test_collection_operations() {
200        let col = Collection::new(
201            "test".to_string(),
202            3,
203            DistanceMetric::Cosine,
204            default_config(),
205        )
206        .unwrap();
207
208        col.insert("vec1", &[1.0, 0.0, 0.0], None).unwrap();
209        col.insert("vec2", &[0.0, 1.0, 0.0], None).unwrap();
210
211        assert_eq!(col.len(), 2);
212        assert!(col.contains("vec1"));
213        assert!(col.contains("vec2"));
214        assert!(!col.contains("vec3"));
215
216        let results = col.search(&[1.0, 0.0, 0.0], 10).unwrap();
217        assert!(!results.is_empty());
218
219        col.delete("vec1").unwrap();
220        assert!(!col.contains("vec1"));
221        assert_eq!(col.len(), 1);
222    }
223
224    #[test]
225    fn test_collection_stats() {
226        let col = Collection::new(
227            "test".to_string(),
228            128,
229            DistanceMetric::Euclidean,
230            HnswConfig::accurate(),
231        )
232        .unwrap();
233
234        col.insert("vec1", &vec![0.0; 128], None).unwrap();
235
236        let stats = col.stats();
237        assert_eq!(stats.name, "test");
238        assert_eq!(stats.vector_count, 1);
239        assert_eq!(stats.dimensions, 128);
240        assert_eq!(stats.metric, DistanceMetric::Euclidean);
241        assert!(stats.memory_bytes > 0);
242    }
243}