ares_vector/
lib.rs

1//! # ares-vector
2//!
3//! A pure-Rust embedded vector database with HNSW (Hierarchical Navigable Small World)
4//! indexing for high-performance approximate nearest neighbor search.
5//!
6//! ## Features
7//!
8//! - **Pure Rust**: No native dependencies, compiles anywhere Rust does
9//! - **HNSW Indexing**: Fast approximate nearest neighbor search
10//! - **Thread-Safe**: Designed for concurrent read/write access
11//! - **Persistence**: Optional disk-based storage with memory-mapped files
12//! - **Multiple Distance Metrics**: Cosine, Euclidean (L2), Dot Product, Manhattan (L1)
13//!
14//! ## Quick Start
15//!
16//! ```rust,ignore
17//! use ares_vector::{VectorDb, Config, DistanceMetric};
18//!
19//! #[tokio::main]
20//! async fn main() -> Result<(), ares_vector::Error> {
21//!     // Create an in-memory database
22//!     let db = VectorDb::open(Config::memory()).await?;
23//!     
24//!     // Create a collection for 384-dimensional vectors
25//!     db.create_collection("documents", 384, DistanceMetric::Cosine).await?;
26//!     
27//!     // Insert vectors
28//!     let embedding = vec![0.1f32; 384];
29//!     db.insert("documents", "doc1", &embedding, None).await?;
30//!     
31//!     // Search for similar vectors
32//!     let query = vec![0.1f32; 384];
33//!     let results = db.search("documents", &query, 10).await?;
34//!     
35//!     Ok(())
36//! }
37//! ```
38//!
39//! ## Architecture
40//!
41//! ```text
42//! ┌─────────────────────────────────────────────────────────────┐
43//! │                         VectorDb                             │
44//! │  ┌─────────────────────────────────────────────────────────┐│
45//! │  │                    Collection                            ││
46//! │  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────┐ ││
47//! │  │  │ HNSW Index  │  │  ID Mapping │  │ Metadata Store  │ ││
48//! │  │  │  (search)   │  │ (str → u64) │  │  (optional)     │ ││
49//! │  │  └─────────────┘  └─────────────┘  └─────────────────┘ ││
50//! │  └─────────────────────────────────────────────────────────┘│
51//! │                                                              │
52//! │  ┌─────────────────────────────────────────────────────────┐│
53//! │  │               Persistence Layer (optional)               ││
54//! │  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────┐ ││
55//! │  │  │   Bincode   │  │  Snapshots  │  │  WAL (future)   │ ││
56//! │  │  └─────────────┘  └─────────────┘  └─────────────────┘ ││
57//! │  └─────────────────────────────────────────────────────────┘│
58//! └─────────────────────────────────────────────────────────────┘
59//! ```
60
61#![warn(missing_docs)]
62#![warn(clippy::all)]
63
64pub mod collection;
65pub mod config;
66pub mod distance;
67pub mod error;
68pub mod index;
69pub mod persistence;
70pub mod types;
71
72// Re-exports for convenience
73pub use collection::Collection;
74pub use config::Config;
75pub use distance::DistanceMetric;
76pub use error::{Error, Result};
77pub use types::{SearchResult, VectorId, VectorMetadata};
78
79use std::path::PathBuf;
80use std::sync::Arc;
81use tracing::{debug, info, instrument, warn};
82
83/// The main vector database instance.
84///
85/// `VectorDb` manages multiple collections, each containing vectors of a specific
86/// dimensionality. It provides thread-safe access to all operations.
87///
88/// # Thread Safety
89///
90/// All operations on `VectorDb` are thread-safe. Uses `scc::HashMap` for
91/// lock-free concurrent access that is safe across `.await` points.
92/// Multiple readers can access the database concurrently, and write
93/// operations use fine-grained locking per entry.
94#[derive(Clone)]
95pub struct VectorDb {
96    inner: Arc<VectorDbInner>,
97}
98
99struct VectorDbInner {
100    config: Config,
101    /// Async-safe concurrent hashmap from scc crate
102    collections: scc::HashMap<String, Arc<Collection>>,
103}
104
105impl VectorDb {
106    /// Open or create a vector database with the given configuration.
107    ///
108    /// # Arguments
109    ///
110    /// * `config` - Database configuration (memory or persistent).
111    ///
112    /// # Example
113    ///
114    /// ```rust,ignore
115    /// // In-memory database
116    /// let db = VectorDb::open(Config::memory()).await?;
117    ///
118    /// // Persistent database
119    /// let db = VectorDb::open(Config::persistent("./data/vectors")).await?;
120    /// ```
121    #[instrument(skip(config), fields(persistent = config.data_path.is_some()))]
122    pub async fn open(config: Config) -> Result<Self> {
123        info!("Opening vector database");
124
125        let db = Self {
126            inner: Arc::new(VectorDbInner {
127                config: config.clone(),
128                collections: scc::HashMap::new(),
129            }),
130        };
131
132        // Load existing collections from disk if persistent
133        if let Some(ref path) = config.data_path {
134            db.load_collections(path).await?;
135        }
136
137        Ok(db)
138    }
139
140    /// Create a new collection with the specified parameters.
141    ///
142    /// # Arguments
143    ///
144    /// * `name` - Unique name for the collection.
145    /// * `dimensions` - Dimensionality of vectors (e.g., 384 for BGE-small).
146    /// * `metric` - Distance metric to use for similarity calculations.
147    ///
148    /// # Errors
149    ///
150    /// Returns an error if a collection with the same name already exists.
151    #[instrument(skip(self))]
152    pub async fn create_collection(
153        &self,
154        name: &str,
155        dimensions: usize,
156        metric: DistanceMetric,
157    ) -> Result<()> {
158        info!(name, dimensions, ?metric, "Creating collection");
159
160        // Check if collection already exists (lock-free read)
161        if self.inner.collections.contains(name) {
162            return Err(Error::CollectionExists(name.to_string()));
163        }
164
165        let collection = Collection::new(
166            name.to_string(),
167            dimensions,
168            metric,
169            self.inner.config.hnsw_config.clone(),
170        )?;
171
172        // Insert returns Err if key already exists (handles race condition)
173        if self.inner.collections.insert(name.to_string(), Arc::new(collection)).is_err() {
174            return Err(Error::CollectionExists(name.to_string()));
175        }
176
177        // Persist if configured
178        if let Some(ref path) = self.inner.config.data_path {
179            self.persist_collection_metadata(path, name).await?;
180        }
181
182        Ok(())
183    }
184
185    /// Delete a collection and all its data.
186    ///
187    /// # Arguments
188    ///
189    /// * `name` - Name of the collection to delete.
190    ///
191    /// # Errors
192    ///
193    /// Returns an error if the collection doesn't exist.
194    #[instrument(skip(self))]
195    pub async fn delete_collection(&self, name: &str) -> Result<()> {
196        info!(name, "Deleting collection");
197
198        // remove returns Option<(K, V)>
199        if self.inner.collections.remove(name).is_none() {
200            return Err(Error::CollectionNotFound(name.to_string()));
201        }
202
203        // Remove from disk if persistent
204        if let Some(ref path) = self.inner.config.data_path {
205            self.delete_collection_files(path, name).await?;
206        }
207
208        Ok(())
209    }
210
211    /// Check if a collection exists.
212    pub fn collection_exists(&self, name: &str) -> bool {
213        self.inner.collections.contains(name)
214    }
215
216    /// List all collection names.
217    pub fn list_collections(&self) -> Vec<String> {
218        let mut names = Vec::new();
219        self.inner.collections.scan(|k, _| {
220            names.push(k.clone());
221        });
222        names
223    }
224
225    /// Get a reference to a collection.
226    ///
227    /// # Arguments
228    ///
229    /// * `name` - Name of the collection.
230    ///
231    /// # Errors
232    ///
233    /// Returns an error if the collection doesn't exist.
234    pub fn get_collection(&self, name: &str) -> Result<Arc<Collection>> {
235        self.inner
236            .collections
237            .read(name, |_, v| v.clone())
238            .ok_or_else(|| Error::CollectionNotFound(name.to_string()))
239    }
240
241    /// Insert a vector into a collection.
242    ///
243    /// # Arguments
244    ///
245    /// * `collection` - Name of the collection.
246    /// * `id` - Unique string identifier for the vector.
247    /// * `vector` - The embedding vector to insert.
248    /// * `metadata` - Optional metadata to associate with the vector.
249    ///
250    /// # Errors
251    ///
252    /// Returns an error if the collection doesn't exist or the vector
253    /// dimensions don't match the collection.
254    #[instrument(skip(self, vector, metadata), fields(collection, id, dim = vector.len()))]
255    pub async fn insert(
256        &self,
257        collection: &str,
258        id: &str,
259        vector: &[f32],
260        metadata: Option<VectorMetadata>,
261    ) -> Result<()> {
262        let col = self.get_collection(collection)?;
263        col.insert(id, vector, metadata)?;
264        debug!("Inserted vector");
265        Ok(())
266    }
267
268    /// Insert multiple vectors into a collection.
269    ///
270    /// This is more efficient than calling `insert` repeatedly as it batches
271    /// the index updates.
272    ///
273    /// # Arguments
274    ///
275    /// * `collection` - Name of the collection.
276    /// * `vectors` - Iterator of (id, vector, metadata) tuples.
277    ///
278    /// # Returns
279    ///
280    /// The number of vectors successfully inserted.
281    #[instrument(skip(self, vectors), fields(collection))]
282    pub async fn insert_batch<'a, I>(&self, collection: &str, vectors: I) -> Result<usize>
283    where
284        I: IntoIterator<Item = (&'a str, &'a [f32], Option<VectorMetadata>)>,
285    {
286        let col = self.get_collection(collection)?;
287        let count = col.insert_batch(vectors)?;
288        debug!(count, "Inserted batch");
289        Ok(count)
290    }
291
292    /// Update a vector in a collection.
293    ///
294    /// This is equivalent to delete + insert but may be more efficient
295    /// for some index implementations.
296    #[instrument(skip(self, vector, metadata), fields(collection, id))]
297    pub async fn update(
298        &self,
299        collection: &str,
300        id: &str,
301        vector: &[f32],
302        metadata: Option<VectorMetadata>,
303    ) -> Result<()> {
304        let col = self.get_collection(collection)?;
305        col.update(id, vector, metadata)?;
306        Ok(())
307    }
308
309    /// Delete a vector from a collection.
310    ///
311    /// # Arguments
312    ///
313    /// * `collection` - Name of the collection.
314    /// * `id` - ID of the vector to delete.
315    ///
316    /// # Returns
317    ///
318    /// `true` if the vector was found and deleted, `false` if it didn't exist.
319    #[instrument(skip(self), fields(collection, id))]
320    pub async fn delete(&self, collection: &str, id: &str) -> Result<bool> {
321        let col = self.get_collection(collection)?;
322        let deleted = col.delete(id)?;
323        debug!(deleted, "Delete result");
324        Ok(deleted)
325    }
326
327    /// Delete multiple vectors from a collection.
328    ///
329    /// # Returns
330    ///
331    /// The number of vectors actually deleted.
332    #[instrument(skip(self, ids), fields(collection, count = ids.len()))]
333    pub async fn delete_batch(&self, collection: &str, ids: &[&str]) -> Result<usize> {
334        let col = self.get_collection(collection)?;
335        let count = col.delete_batch(ids)?;
336        debug!(count, "Deleted batch");
337        Ok(count)
338    }
339
340    /// Search for similar vectors.
341    ///
342    /// # Arguments
343    ///
344    /// * `collection` - Name of the collection to search.
345    /// * `query` - Query vector to find similar vectors to.
346    /// * `limit` - Maximum number of results to return.
347    ///
348    /// # Returns
349    ///
350    /// A vector of search results, sorted by similarity (best first).
351    #[instrument(skip(self, query), fields(collection, limit, dim = query.len()))]
352    pub async fn search(
353        &self,
354        collection: &str,
355        query: &[f32],
356        limit: usize,
357    ) -> Result<Vec<SearchResult>> {
358        let col = self.get_collection(collection)?;
359        let results = col.search(query, limit)?;
360        debug!(count = results.len(), "Search completed");
361        Ok(results)
362    }
363
364    /// Search with a minimum score threshold.
365    ///
366    /// # Arguments
367    ///
368    /// * `collection` - Name of the collection.
369    /// * `query` - Query vector.
370    /// * `limit` - Maximum results.
371    /// * `min_score` - Minimum similarity score (0.0 to 1.0 for cosine).
372    #[instrument(skip(self, query), fields(collection, limit, min_score))]
373    pub async fn search_with_threshold(
374        &self,
375        collection: &str,
376        query: &[f32],
377        limit: usize,
378        min_score: f32,
379    ) -> Result<Vec<SearchResult>> {
380        let col = self.get_collection(collection)?;
381        let results = col.search_with_threshold(query, limit, min_score)?;
382        Ok(results)
383    }
384
385    /// Get a vector by ID.
386    ///
387    /// # Returns
388    ///
389    /// The vector and its metadata if found.
390    pub async fn get(&self, collection: &str, id: &str) -> Result<Option<(Vec<f32>, Option<VectorMetadata>)>> {
391        let col = self.get_collection(collection)?;
392        Ok(col.get(id))
393    }
394
395    /// Check if a vector exists.
396    pub fn contains(&self, collection: &str, id: &str) -> Result<bool> {
397        let col = self.get_collection(collection)?;
398        Ok(col.contains(id))
399    }
400
401    /// Get the number of vectors in a collection.
402    pub fn count(&self, collection: &str) -> Result<usize> {
403        let col = self.get_collection(collection)?;
404        Ok(col.len())
405    }
406
407    /// Get collection statistics.
408    pub fn collection_stats(&self, collection: &str) -> Result<CollectionStats> {
409        let col = self.get_collection(collection)?;
410        Ok(col.stats())
411    }
412
413    /// Persist the current state to disk.
414    ///
415    /// This is only relevant for persistent databases. For in-memory databases,
416    /// this is a no-op.
417    #[instrument(skip(self))]
418    pub async fn persist(&self) -> Result<()> {
419        let Some(ref path) = self.inner.config.data_path else {
420            debug!("Skipping persist for in-memory database");
421            return Ok(());
422        };
423
424        info!("Persisting database to disk");
425        
426        // Collect names and collections for persistence
427        let mut to_persist: Vec<(String, Arc<Collection>)> = Vec::new();
428        self.inner.collections.scan(|name, collection| {
429            to_persist.push((name.clone(), collection.clone()));
430        });
431
432        for (name, collection) in to_persist {
433            self.persist_collection(path, &name, &collection).await?;
434        }
435
436        Ok(())
437    }
438
439    /// Force a compaction of the HNSW indices.
440    ///
441    /// This can reclaim space after many deletions.
442    #[instrument(skip(self))]
443    pub async fn compact(&self, collection: &str) -> Result<()> {
444        let col = self.get_collection(collection)?;
445        col.compact()?;
446        Ok(())
447    }
448
449    // Internal: Load collections from disk
450    async fn load_collections(&self, path: &PathBuf) -> Result<()> {
451        if !path.exists() {
452            tokio::fs::create_dir_all(path).await?;
453            return Ok(());
454        }
455
456        // Load collection metadata and indices
457        let metadata_path = path.join("collections.json");
458        if !metadata_path.exists() {
459            return Ok(());
460        }
461
462        let data = tokio::fs::read_to_string(&metadata_path).await?;
463        let collection_names: Vec<String> = serde_json::from_str(&data)
464            .map_err(|e| Error::Persistence(format!("Failed to parse collections.json: {}", e)))?;
465
466        for name in collection_names {
467            match self.load_collection(path, &name).await {
468                Ok(collection) => {
469                    // scc::HashMap::insert returns Err if key exists, Ok otherwise
470                    let _ = self.inner.collections.insert(name.clone(), Arc::new(collection));
471                    info!(name, "Loaded collection");
472                }
473                Err(e) => {
474                    warn!(name, error = %e, "Failed to load collection, skipping");
475                }
476            }
477        }
478
479        Ok(())
480    }
481
482    async fn load_collection(&self, base_path: &PathBuf, name: &str) -> Result<Collection> {
483        persistence::load_collection(base_path, name).await
484    }
485
486    async fn persist_collection(
487        &self,
488        base_path: &PathBuf,
489        name: &str,
490        collection: &Collection,
491    ) -> Result<()> {
492        persistence::save_collection(base_path, name, collection).await
493    }
494
495    async fn persist_collection_metadata(&self, base_path: &PathBuf, _name: &str) -> Result<()> {
496        let collections = self.list_collections();
497        let metadata_path = base_path.join("collections.json");
498        let data = serde_json::to_string_pretty(&collections)
499            .map_err(|e| Error::Persistence(format!("Failed to serialize collections: {}", e)))?;
500        tokio::fs::write(&metadata_path, data).await?;
501        Ok(())
502    }
503
504    async fn delete_collection_files(&self, base_path: &PathBuf, name: &str) -> Result<()> {
505        let collection_path = base_path.join(name);
506        if collection_path.exists() {
507            tokio::fs::remove_dir_all(&collection_path).await?;
508        }
509        // Update metadata
510        self.persist_collection_metadata(base_path, name).await?;
511        Ok(())
512    }
513}
514
515/// Statistics about a collection.
516#[derive(Debug, Clone)]
517#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
518pub struct CollectionStats {
519    /// Name of the collection.
520    pub name: String,
521    /// Number of vectors in the collection.
522    pub vector_count: usize,
523    /// Dimensionality of vectors.
524    pub dimensions: usize,
525    /// Distance metric used.
526    pub metric: DistanceMetric,
527    /// Approximate memory usage in bytes.
528    pub memory_bytes: usize,
529    /// HNSW index parameters.
530    pub hnsw_params: HnswParams,
531}
532
533/// HNSW index parameters.
534#[derive(Debug, Clone)]
535#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
536pub struct HnswParams {
537    /// Maximum number of connections per layer.
538    pub m: usize,
539    /// Size of the dynamic candidate list during construction.
540    pub ef_construction: usize,
541    /// Size of the dynamic candidate list during search.
542    pub ef_search: usize,
543}
544
545// Required for serde_json usage
546use serde_json;
547
548#[cfg(test)]
549mod tests {
550    use super::*;
551
552    #[tokio::test]
553    async fn test_create_and_search() {
554        let db = VectorDb::open(Config::memory()).await.unwrap();
555
556        db.create_collection("test", 3, DistanceMetric::Cosine)
557            .await
558            .unwrap();
559
560        db.insert("test", "vec1", &[1.0, 0.0, 0.0], None)
561            .await
562            .unwrap();
563        db.insert("test", "vec2", &[0.0, 1.0, 0.0], None)
564            .await
565            .unwrap();
566        db.insert("test", "vec3", &[0.9, 0.1, 0.0], None)
567            .await
568            .unwrap();
569
570        let results = db.search("test", &[1.0, 0.0, 0.0], 10).await.unwrap();
571
572        assert!(!results.is_empty());
573        assert_eq!(results[0].id, "vec1");
574    }
575
576    #[tokio::test]
577    async fn test_collection_lifecycle() {
578        let db = VectorDb::open(Config::memory()).await.unwrap();
579
580        assert!(!db.collection_exists("test"));
581
582        db.create_collection("test", 128, DistanceMetric::Euclidean)
583            .await
584            .unwrap();
585        assert!(db.collection_exists("test"));
586
587        db.delete_collection("test").await.unwrap();
588        assert!(!db.collection_exists("test"));
589    }
590
591    #[tokio::test]
592    async fn test_duplicate_collection_error() {
593        let db = VectorDb::open(Config::memory()).await.unwrap();
594
595        db.create_collection("test", 128, DistanceMetric::Cosine)
596            .await
597            .unwrap();
598
599        let result = db
600            .create_collection("test", 128, DistanceMetric::Cosine)
601            .await;
602        assert!(matches!(result, Err(Error::CollectionExists(_))));
603    }
604}