Skip to main content

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