Skip to main content

ares_vector/
types.rs

1//! Common types for ares-vector.
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6/// Unique identifier for a vector in a collection.
7pub type VectorId = String;
8
9/// Metadata associated with a vector.
10///
11/// Arbitrary key-value pairs that can be stored alongside vectors.
12#[derive(Debug, Clone, Default, Serialize, Deserialize)]
13pub struct VectorMetadata {
14    /// Key-value pairs of metadata.
15    pub data: HashMap<String, MetadataValue>,
16}
17
18impl VectorMetadata {
19    /// Create empty metadata.
20    pub fn new() -> Self {
21        Self {
22            data: HashMap::new(),
23        }
24    }
25
26    /// Create metadata from a list of key-value pairs.
27    pub fn from_pairs<I, K, V>(pairs: I) -> Self
28    where
29        I: IntoIterator<Item = (K, V)>,
30        K: Into<String>,
31        V: Into<MetadataValue>,
32    {
33        Self {
34            data: pairs
35                .into_iter()
36                .map(|(k, v)| (k.into(), v.into()))
37                .collect(),
38        }
39    }
40
41    /// Insert a key-value pair.
42    pub fn insert<K: Into<String>, V: Into<MetadataValue>>(&mut self, key: K, value: V) {
43        self.data.insert(key.into(), value.into());
44    }
45
46    /// Get a value by key.
47    pub fn get(&self, key: &str) -> Option<&MetadataValue> {
48        self.data.get(key)
49    }
50
51    /// Get a string value by key.
52    pub fn get_string(&self, key: &str) -> Option<&str> {
53        match self.data.get(key)? {
54            MetadataValue::String(s) => Some(s),
55            _ => None,
56        }
57    }
58
59    /// Get an integer value by key.
60    pub fn get_int(&self, key: &str) -> Option<i64> {
61        match self.data.get(key)? {
62            MetadataValue::Int(i) => Some(*i),
63            _ => None,
64        }
65    }
66
67    /// Get a float value by key.
68    pub fn get_float(&self, key: &str) -> Option<f64> {
69        match self.data.get(key)? {
70            MetadataValue::Float(f) => Some(*f),
71            _ => None,
72        }
73    }
74
75    /// Get a boolean value by key.
76    pub fn get_bool(&self, key: &str) -> Option<bool> {
77        match self.data.get(key)? {
78            MetadataValue::Bool(b) => Some(*b),
79            _ => None,
80        }
81    }
82
83    /// Check if metadata is empty.
84    pub fn is_empty(&self) -> bool {
85        self.data.is_empty()
86    }
87
88    /// Get the number of metadata entries.
89    pub fn len(&self) -> usize {
90        self.data.len()
91    }
92}
93
94/// A metadata value.
95#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
96pub enum MetadataValue {
97    /// String value.
98    String(String),
99    /// Integer value.
100    Int(i64),
101    /// Float value.
102    Float(f64),
103    /// Boolean value.
104    Bool(bool),
105    /// List of values.
106    List(Vec<MetadataValue>),
107}
108
109impl From<String> for MetadataValue {
110    fn from(s: String) -> Self {
111        MetadataValue::String(s)
112    }
113}
114
115impl From<&str> for MetadataValue {
116    fn from(s: &str) -> Self {
117        MetadataValue::String(s.to_string())
118    }
119}
120
121impl From<i64> for MetadataValue {
122    fn from(i: i64) -> Self {
123        MetadataValue::Int(i)
124    }
125}
126
127impl From<i32> for MetadataValue {
128    fn from(i: i32) -> Self {
129        MetadataValue::Int(i as i64)
130    }
131}
132
133impl From<f64> for MetadataValue {
134    fn from(f: f64) -> Self {
135        MetadataValue::Float(f)
136    }
137}
138
139impl From<f32> for MetadataValue {
140    fn from(f: f32) -> Self {
141        MetadataValue::Float(f as f64)
142    }
143}
144
145impl From<bool> for MetadataValue {
146    fn from(b: bool) -> Self {
147        MetadataValue::Bool(b)
148    }
149}
150
151impl<T: Into<MetadataValue>> From<Vec<T>> for MetadataValue {
152    fn from(v: Vec<T>) -> Self {
153        MetadataValue::List(v.into_iter().map(Into::into).collect())
154    }
155}
156
157/// Result of a vector search.
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct SearchResult {
160    /// ID of the matched vector.
161    pub id: VectorId,
162    /// Similarity score (higher = more similar for most metrics).
163    pub score: f32,
164    /// Optional metadata associated with the vector.
165    pub metadata: Option<VectorMetadata>,
166}
167
168impl SearchResult {
169    /// Create a new search result.
170    pub fn new(id: VectorId, score: f32, metadata: Option<VectorMetadata>) -> Self {
171        Self {
172            id,
173            score,
174            metadata,
175        }
176    }
177}
178
179/// Internal representation of a stored vector.
180#[allow(dead_code)]
181#[derive(Debug, Clone, Serialize, Deserialize)]
182pub(crate) struct StoredVector {
183    /// External string ID.
184    pub id: VectorId,
185    /// Internal numeric ID for HNSW.
186    pub internal_id: usize,
187    /// The vector data.
188    pub vector: Vec<f32>,
189    /// Optional metadata.
190    pub metadata: Option<VectorMetadata>,
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    #[test]
198    fn test_metadata_basic() {
199        let mut meta = VectorMetadata::new();
200        meta.insert("title", "Test Document");
201        meta.insert("score", 0.95f64);
202        meta.insert("count", 42i64);
203        meta.insert("active", true);
204
205        assert_eq!(meta.get_string("title"), Some("Test Document"));
206        assert_eq!(meta.get_float("score"), Some(0.95));
207        assert_eq!(meta.get_int("count"), Some(42));
208        assert_eq!(meta.get_bool("active"), Some(true));
209    }
210
211    #[test]
212    fn test_metadata_from_pairs() {
213        let meta = VectorMetadata::from_pairs([
214            ("key1", MetadataValue::String("value1".to_string())),
215            ("key2", MetadataValue::Int(123)),
216        ]);
217
218        assert_eq!(meta.len(), 2);
219        assert_eq!(meta.get_string("key1"), Some("value1"));
220        assert_eq!(meta.get_int("key2"), Some(123));
221    }
222
223    #[test]
224    fn test_search_result() {
225        let result = SearchResult::new(
226            "doc1".to_string(),
227            0.95,
228            Some(VectorMetadata::from_pairs([(
229                "title",
230                MetadataValue::String("Test".to_string()),
231            )])),
232        );
233
234        assert_eq!(result.id, "doc1");
235        assert_eq!(result.score, 0.95);
236        assert!(result.metadata.is_some());
237
238        let bare = SearchResult::new("doc2".to_string(), 0.5, None);
239        assert!(bare.metadata.is_none());
240    }
241
242    #[test]
243    fn test_metadata_get_and_empty() {
244        let empty = VectorMetadata::new();
245        assert!(empty.is_empty());
246        assert_eq!(empty.len(), 0);
247        assert!(empty.get("missing").is_none());
248
249        let mut meta = VectorMetadata::new();
250        meta.insert("tag", "alpha");
251        assert!(!meta.is_empty());
252        assert_eq!(meta.len(), 1);
253        assert_eq!(
254            meta.get("tag"),
255            Some(&MetadataValue::String("alpha".to_string()))
256        );
257        assert!(meta.get("missing").is_none());
258    }
259
260    #[test]
261    fn test_metadata_typed_getters_wrong_type() {
262        let mut meta = VectorMetadata::new();
263        meta.insert("name", "hello");
264        meta.insert("count", 7i64);
265        meta.insert("ratio", 0.5f64);
266        meta.insert("active", false);
267
268        assert_eq!(meta.get_string("name"), Some("hello"));
269        assert_eq!(meta.get_string("count"), None);
270        assert_eq!(meta.get_int("count"), Some(7));
271        assert_eq!(meta.get_int("name"), None);
272        assert_eq!(meta.get_float("ratio"), Some(0.5));
273        assert_eq!(meta.get_float("count"), None);
274        assert_eq!(meta.get_bool("active"), Some(false));
275        assert_eq!(meta.get_bool("ratio"), None);
276    }
277
278    #[test]
279    fn test_metadata_value_from_impls() {
280        let from_string: MetadataValue = MetadataValue::from(String::from("text"));
281        let from_str: MetadataValue = "text".into();
282        let from_i32: MetadataValue = 42i32.into();
283        let from_i64: MetadataValue = 99i64.into();
284        let from_f32: MetadataValue = 1.5f32.into();
285        let from_f64: MetadataValue = 2.5f64.into();
286        let from_bool: MetadataValue = true.into();
287        let from_list: MetadataValue = vec!["a", "b"].into();
288
289        assert_eq!(from_string, MetadataValue::String("text".to_string()));
290        assert_eq!(from_str, MetadataValue::String("text".to_string()));
291        assert_eq!(from_i32, MetadataValue::Int(42));
292        assert_eq!(from_i64, MetadataValue::Int(99));
293        assert_eq!(from_f32, MetadataValue::Float(1.5));
294        assert_eq!(from_f64, MetadataValue::Float(2.5));
295        assert_eq!(from_bool, MetadataValue::Bool(true));
296        assert_eq!(
297            from_list,
298            MetadataValue::List(vec![
299                MetadataValue::String("a".to_string()),
300                MetadataValue::String("b".to_string()),
301            ])
302        );
303    }
304
305    #[test]
306    fn test_stored_vector_roundtrip() {
307        let stored = StoredVector {
308            id: "vec-1".to_string(),
309            internal_id: 0,
310            vector: vec![1.0, 2.0, 3.0],
311            metadata: Some(VectorMetadata::from_pairs([("k", "v")])),
312        };
313        let json = serde_json::to_string(&stored).unwrap();
314        let decoded: StoredVector = serde_json::from_str(&json).unwrap();
315        assert_eq!(decoded.id, "vec-1");
316        assert_eq!(decoded.internal_id, 0);
317        assert_eq!(decoded.vector, vec![1.0, 2.0, 3.0]);
318        assert_eq!(decoded.metadata.as_ref().unwrap().get_string("k"), Some("v"));
319    }
320}