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}