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.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
35        }
36    }
37
38    /// Insert a key-value pair.
39    pub fn insert<K: Into<String>, V: Into<MetadataValue>>(&mut self, key: K, value: V) {
40        self.data.insert(key.into(), value.into());
41    }
42
43    /// Get a value by key.
44    pub fn get(&self, key: &str) -> Option<&MetadataValue> {
45        self.data.get(key)
46    }
47
48    /// Get a string value by key.
49    pub fn get_string(&self, key: &str) -> Option<&str> {
50        match self.data.get(key)? {
51            MetadataValue::String(s) => Some(s),
52            _ => None,
53        }
54    }
55
56    /// Get an integer value by key.
57    pub fn get_int(&self, key: &str) -> Option<i64> {
58        match self.data.get(key)? {
59            MetadataValue::Int(i) => Some(*i),
60            _ => None,
61        }
62    }
63
64    /// Get a float value by key.
65    pub fn get_float(&self, key: &str) -> Option<f64> {
66        match self.data.get(key)? {
67            MetadataValue::Float(f) => Some(*f),
68            _ => None,
69        }
70    }
71
72    /// Get a boolean value by key.
73    pub fn get_bool(&self, key: &str) -> Option<bool> {
74        match self.data.get(key)? {
75            MetadataValue::Bool(b) => Some(*b),
76            _ => None,
77        }
78    }
79
80    /// Check if metadata is empty.
81    pub fn is_empty(&self) -> bool {
82        self.data.is_empty()
83    }
84
85    /// Get the number of metadata entries.
86    pub fn len(&self) -> usize {
87        self.data.len()
88    }
89}
90
91/// A metadata value.
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93pub enum MetadataValue {
94    /// String value.
95    String(String),
96    /// Integer value.
97    Int(i64),
98    /// Float value.
99    Float(f64),
100    /// Boolean value.
101    Bool(bool),
102    /// List of values.
103    List(Vec<MetadataValue>),
104}
105
106impl From<String> for MetadataValue {
107    fn from(s: String) -> Self {
108        MetadataValue::String(s)
109    }
110}
111
112impl From<&str> for MetadataValue {
113    fn from(s: &str) -> Self {
114        MetadataValue::String(s.to_string())
115    }
116}
117
118impl From<i64> for MetadataValue {
119    fn from(i: i64) -> Self {
120        MetadataValue::Int(i)
121    }
122}
123
124impl From<i32> for MetadataValue {
125    fn from(i: i32) -> Self {
126        MetadataValue::Int(i as i64)
127    }
128}
129
130impl From<f64> for MetadataValue {
131    fn from(f: f64) -> Self {
132        MetadataValue::Float(f)
133    }
134}
135
136impl From<f32> for MetadataValue {
137    fn from(f: f32) -> Self {
138        MetadataValue::Float(f as f64)
139    }
140}
141
142impl From<bool> for MetadataValue {
143    fn from(b: bool) -> Self {
144        MetadataValue::Bool(b)
145    }
146}
147
148impl<T: Into<MetadataValue>> From<Vec<T>> for MetadataValue {
149    fn from(v: Vec<T>) -> Self {
150        MetadataValue::List(v.into_iter().map(Into::into).collect())
151    }
152}
153
154/// Result of a vector search.
155#[derive(Debug, Clone, Serialize, Deserialize)]
156pub struct SearchResult {
157    /// ID of the matched vector.
158    pub id: VectorId,
159    /// Similarity score (higher = more similar for most metrics).
160    pub score: f32,
161    /// Optional metadata associated with the vector.
162    pub metadata: Option<VectorMetadata>,
163}
164
165impl SearchResult {
166    /// Create a new search result.
167    pub fn new(id: VectorId, score: f32, metadata: Option<VectorMetadata>) -> Self {
168        Self { id, score, metadata }
169    }
170}
171
172/// Internal representation of a stored vector.
173#[allow(dead_code)]
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub(crate) struct StoredVector {
176    /// External string ID.
177    pub id: VectorId,
178    /// Internal numeric ID for HNSW.
179    pub internal_id: usize,
180    /// The vector data.
181    pub vector: Vec<f32>,
182    /// Optional metadata.
183    pub metadata: Option<VectorMetadata>,
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn test_metadata_basic() {
192        let mut meta = VectorMetadata::new();
193        meta.insert("title", "Test Document");
194        meta.insert("score", 0.95f64);
195        meta.insert("count", 42i64);
196        meta.insert("active", true);
197
198        assert_eq!(meta.get_string("title"), Some("Test Document"));
199        assert_eq!(meta.get_float("score"), Some(0.95));
200        assert_eq!(meta.get_int("count"), Some(42));
201        assert_eq!(meta.get_bool("active"), Some(true));
202    }
203
204    #[test]
205    fn test_metadata_from_pairs() {
206        let meta = VectorMetadata::from_pairs([
207            ("key1", MetadataValue::String("value1".to_string())),
208            ("key2", MetadataValue::Int(123)),
209        ]);
210
211        assert_eq!(meta.len(), 2);
212        assert_eq!(meta.get_string("key1"), Some("value1"));
213        assert_eq!(meta.get_int("key2"), Some(123));
214    }
215
216    #[test]
217    fn test_search_result() {
218        let result = SearchResult::new(
219            "doc1".to_string(),
220            0.95,
221            Some(VectorMetadata::from_pairs([("title", MetadataValue::String("Test".to_string()))])),
222        );
223
224        assert_eq!(result.id, "doc1");
225        assert_eq!(result.score, 0.95);
226        assert!(result.metadata.is_some());
227    }
228}