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::DistanceMetric;
76pub use error::{Error, Result};
77pub use types::{SearchResult, VectorId, VectorMetadata};
78
79use std::path::Path;
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
174            .inner
175            .collections
176            .insert(name.to_string(), Arc::new(collection))
177            .is_err()
178        {
179            return Err(Error::CollectionExists(name.to_string()));
180        }
181
182        // Persist if configured
183        if let Some(ref path) = self.inner.config.data_path {
184            self.persist_collection_metadata(path, name).await?;
185        }
186
187        Ok(())
188    }
189
190    /// Delete a collection and all its data.
191    ///
192    /// # Arguments
193    ///
194    /// * `name` - Name of the collection to delete.
195    ///
196    /// # Errors
197    ///
198    /// Returns an error if the collection doesn't exist.
199    #[instrument(skip(self))]
200    pub async fn delete_collection(&self, name: &str) -> Result<()> {
201        info!(name, "Deleting collection");
202
203        // remove returns Option<(K, V)>
204        if self.inner.collections.remove(name).is_none() {
205            return Err(Error::CollectionNotFound(name.to_string()));
206        }
207
208        // Remove from disk if persistent
209        if let Some(ref path) = self.inner.config.data_path {
210            self.delete_collection_files(path, name).await?;
211        }
212
213        Ok(())
214    }
215
216    /// Check if a collection exists.
217    pub fn collection_exists(&self, name: &str) -> bool {
218        self.inner.collections.contains(name)
219    }
220
221    /// List all collection names.
222    pub fn list_collections(&self) -> Vec<String> {
223        let mut names = Vec::new();
224        self.inner.collections.scan(|k, _| {
225            names.push(k.clone());
226        });
227        names
228    }
229
230    /// Get a reference to a collection.
231    ///
232    /// # Arguments
233    ///
234    /// * `name` - Name of the collection.
235    ///
236    /// # Errors
237    ///
238    /// Returns an error if the collection doesn't exist.
239    pub fn get_collection(&self, name: &str) -> Result<Arc<Collection>> {
240        self.inner
241            .collections
242            .read(name, |_, v| v.clone())
243            .ok_or_else(|| Error::CollectionNotFound(name.to_string()))
244    }
245
246    /// Insert a vector into a collection.
247    ///
248    /// # Arguments
249    ///
250    /// * `collection` - Name of the collection.
251    /// * `id` - Unique string identifier for the vector.
252    /// * `vector` - The embedding vector to insert.
253    /// * `metadata` - Optional metadata to associate with the vector.
254    ///
255    /// # Errors
256    ///
257    /// Returns an error if the collection doesn't exist or the vector
258    /// dimensions don't match the collection.
259    #[instrument(skip(self, vector, metadata), fields(collection, id, dim = vector.len()))]
260    pub async fn insert(
261        &self,
262        collection: &str,
263        id: &str,
264        vector: &[f32],
265        metadata: Option<VectorMetadata>,
266    ) -> Result<()> {
267        let col = self.get_collection(collection)?;
268        col.insert(id, vector, metadata)?;
269        debug!("Inserted vector");
270        Ok(())
271    }
272
273    /// Insert multiple vectors into a collection.
274    ///
275    /// This is more efficient than calling `insert` repeatedly as it batches
276    /// the index updates.
277    ///
278    /// # Arguments
279    ///
280    /// * `collection` - Name of the collection.
281    /// * `vectors` - Iterator of (id, vector, metadata) tuples.
282    ///
283    /// # Returns
284    ///
285    /// The number of vectors successfully inserted.
286    #[instrument(skip(self, vectors), fields(collection))]
287    pub async fn insert_batch<'a, I>(&self, collection: &str, vectors: I) -> Result<usize>
288    where
289        I: IntoIterator<Item = (&'a str, &'a [f32], Option<VectorMetadata>)>,
290    {
291        let col = self.get_collection(collection)?;
292        let count = col.insert_batch(vectors)?;
293        debug!(count, "Inserted batch");
294        Ok(count)
295    }
296
297    /// Update a vector in a collection.
298    ///
299    /// This is equivalent to delete + insert but may be more efficient
300    /// for some index implementations.
301    #[instrument(skip(self, vector, metadata), fields(collection, id))]
302    pub async fn update(
303        &self,
304        collection: &str,
305        id: &str,
306        vector: &[f32],
307        metadata: Option<VectorMetadata>,
308    ) -> Result<()> {
309        let col = self.get_collection(collection)?;
310        col.update(id, vector, metadata)?;
311        Ok(())
312    }
313
314    /// Delete a vector from a collection.
315    ///
316    /// # Arguments
317    ///
318    /// * `collection` - Name of the collection.
319    /// * `id` - ID of the vector to delete.
320    ///
321    /// # Returns
322    ///
323    /// `true` if the vector was found and deleted, `false` if it didn't exist.
324    #[instrument(skip(self), fields(collection, id))]
325    pub async fn delete(&self, collection: &str, id: &str) -> Result<bool> {
326        let col = self.get_collection(collection)?;
327        let deleted = col.delete(id)?;
328        debug!(deleted, "Delete result");
329        Ok(deleted)
330    }
331
332    /// Delete multiple vectors from a collection.
333    ///
334    /// # Returns
335    ///
336    /// The number of vectors actually deleted.
337    #[instrument(skip(self, ids), fields(collection, count = ids.len()))]
338    pub async fn delete_batch(&self, collection: &str, ids: &[&str]) -> Result<usize> {
339        let col = self.get_collection(collection)?;
340        let count = col.delete_batch(ids)?;
341        debug!(count, "Deleted batch");
342        Ok(count)
343    }
344
345    /// Search for similar vectors.
346    ///
347    /// # Arguments
348    ///
349    /// * `collection` - Name of the collection to search.
350    /// * `query` - Query vector to find similar vectors to.
351    /// * `limit` - Maximum number of results to return.
352    ///
353    /// # Returns
354    ///
355    /// A vector of search results, sorted by similarity (best first).
356    #[instrument(skip(self, query), fields(collection, limit, dim = query.len()))]
357    pub async fn search(
358        &self,
359        collection: &str,
360        query: &[f32],
361        limit: usize,
362    ) -> Result<Vec<SearchResult>> {
363        let col = self.get_collection(collection)?;
364        let results = col.search(query, limit)?;
365        debug!(count = results.len(), "Search completed");
366        Ok(results)
367    }
368
369    /// Search with a minimum score threshold.
370    ///
371    /// # Arguments
372    ///
373    /// * `collection` - Name of the collection.
374    /// * `query` - Query vector.
375    /// * `limit` - Maximum results.
376    /// * `min_score` - Minimum similarity score (0.0 to 1.0 for cosine).
377    #[instrument(skip(self, query), fields(collection, limit, min_score))]
378    pub async fn search_with_threshold(
379        &self,
380        collection: &str,
381        query: &[f32],
382        limit: usize,
383        min_score: f32,
384    ) -> Result<Vec<SearchResult>> {
385        let col = self.get_collection(collection)?;
386        let results = col.search_with_threshold(query, limit, min_score)?;
387        Ok(results)
388    }
389
390    /// Get a vector by ID.
391    ///
392    /// # Returns
393    ///
394    /// The vector and its metadata if found.
395    pub async fn get(
396        &self,
397        collection: &str,
398        id: &str,
399    ) -> Result<Option<(Vec<f32>, Option<VectorMetadata>)>> {
400        let col = self.get_collection(collection)?;
401        Ok(col.get(id))
402    }
403
404    /// Check if a vector exists.
405    pub fn contains(&self, collection: &str, id: &str) -> Result<bool> {
406        let col = self.get_collection(collection)?;
407        Ok(col.contains(id))
408    }
409
410    /// Get the number of vectors in a collection.
411    pub fn count(&self, collection: &str) -> Result<usize> {
412        let col = self.get_collection(collection)?;
413        Ok(col.len())
414    }
415
416    /// Get collection statistics.
417    pub fn collection_stats(&self, collection: &str) -> Result<CollectionStats> {
418        let col = self.get_collection(collection)?;
419        Ok(col.stats())
420    }
421
422    /// Persist the current state to disk.
423    ///
424    /// This is only relevant for persistent databases. For in-memory databases,
425    /// this is a no-op.
426    #[instrument(skip(self))]
427    pub async fn persist(&self) -> Result<()> {
428        let Some(ref path) = self.inner.config.data_path else {
429            debug!("Skipping persist for in-memory database");
430            return Ok(());
431        };
432
433        info!("Persisting database to disk");
434
435        // Collect names and collections for persistence
436        let mut to_persist: Vec<(String, Arc<Collection>)> = Vec::new();
437        self.inner.collections.scan(|name, collection| {
438            to_persist.push((name.clone(), collection.clone()));
439        });
440
441        for (name, collection) in to_persist {
442            self.persist_collection(path, &name, &collection).await?;
443        }
444
445        Ok(())
446    }
447
448    /// Force a compaction of the HNSW indices.
449    ///
450    /// This can reclaim space after many deletions.
451    #[instrument(skip(self))]
452    pub async fn compact(&self, collection: &str) -> Result<()> {
453        let col = self.get_collection(collection)?;
454        col.compact()?;
455        Ok(())
456    }
457
458    // Internal: Load collections from disk
459    async fn load_collections(&self, path: &Path) -> Result<()> {
460        if !path.exists() {
461            tokio::fs::create_dir_all(path).await?;
462            return Ok(());
463        }
464
465        // Load collection metadata and indices
466        let metadata_path = path.join("collections.json");
467        if !metadata_path.exists() {
468            return Ok(());
469        }
470
471        let data = tokio::fs::read_to_string(&metadata_path).await?;
472        let collection_names: Vec<String> = serde_json::from_str(&data)
473            .map_err(|e| Error::Persistence(format!("Failed to parse collections.json: {}", e)))?;
474
475        for name in collection_names {
476            match self.load_collection(path, &name).await {
477                Ok(collection) => {
478                    // scc::HashMap::insert returns Err if key exists, Ok otherwise
479                    let _ = self
480                        .inner
481                        .collections
482                        .insert(name.clone(), Arc::new(collection));
483                    info!(name, "Loaded collection");
484                }
485                Err(e) => {
486                    warn!(name, error = %e, "Failed to load collection, skipping");
487                }
488            }
489        }
490
491        Ok(())
492    }
493
494    async fn load_collection(&self, base_path: &Path, name: &str) -> Result<Collection> {
495        persistence::load_collection(base_path, name).await
496    }
497
498    async fn persist_collection(
499        &self,
500        base_path: &Path,
501        name: &str,
502        collection: &Collection,
503    ) -> Result<()> {
504        persistence::save_collection(base_path, name, collection).await
505    }
506
507    async fn persist_collection_metadata(&self, base_path: &Path, _name: &str) -> Result<()> {
508        let collections = self.list_collections();
509        let metadata_path = base_path.join("collections.json");
510        let data = serde_json::to_string_pretty(&collections)
511            .map_err(|e| Error::Persistence(format!("Failed to serialize collections: {}", e)))?;
512        tokio::fs::write(&metadata_path, data).await?;
513        Ok(())
514    }
515
516    async fn delete_collection_files(&self, base_path: &Path, name: &str) -> Result<()> {
517        let collection_path = base_path.join(name);
518        if collection_path.exists() {
519            tokio::fs::remove_dir_all(&collection_path).await?;
520        }
521        // Update metadata
522        self.persist_collection_metadata(base_path, name).await?;
523        Ok(())
524    }
525}
526
527/// Statistics about a collection.
528#[derive(Debug, Clone)]
529#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
530pub struct CollectionStats {
531    /// Name of the collection.
532    pub name: String,
533    /// Number of vectors in the collection.
534    pub vector_count: usize,
535    /// Dimensionality of vectors.
536    pub dimensions: usize,
537    /// Distance metric used.
538    pub metric: DistanceMetric,
539    /// Approximate memory usage in bytes.
540    pub memory_bytes: usize,
541    /// HNSW index parameters.
542    pub hnsw_params: HnswParams,
543}
544
545/// HNSW index parameters.
546#[derive(Debug, Clone)]
547#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
548pub struct HnswParams {
549    /// Maximum number of connections per layer.
550    pub m: usize,
551    /// Size of the dynamic candidate list during construction.
552    pub ef_construction: usize,
553    /// Size of the dynamic candidate list during search.
554    pub ef_search: usize,
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560
561    #[tokio::test]
562    async fn test_create_and_search() {
563        let db = VectorDb::open(Config::memory()).await.unwrap();
564
565        db.create_collection("test", 3, DistanceMetric::Cosine)
566            .await
567            .unwrap();
568
569        db.insert("test", "vec1", &[1.0, 0.0, 0.0], None)
570            .await
571            .unwrap();
572        db.insert("test", "vec2", &[0.0, 1.0, 0.0], None)
573            .await
574            .unwrap();
575        db.insert("test", "vec3", &[0.9, 0.1, 0.0], None)
576            .await
577            .unwrap();
578
579        let results = db.search("test", &[1.0, 0.0, 0.0], 10).await.unwrap();
580
581        assert!(!results.is_empty());
582        assert_eq!(results[0].id, "vec1");
583    }
584
585    #[tokio::test]
586    async fn test_collection_lifecycle() {
587        let db = VectorDb::open(Config::memory()).await.unwrap();
588
589        assert!(!db.collection_exists("test"));
590
591        db.create_collection("test", 128, DistanceMetric::Euclidean)
592            .await
593            .unwrap();
594        assert!(db.collection_exists("test"));
595
596        db.delete_collection("test").await.unwrap();
597        assert!(!db.collection_exists("test"));
598    }
599
600    #[tokio::test]
601    async fn test_duplicate_collection_error() {
602        let db = VectorDb::open(Config::memory()).await.unwrap();
603
604        db.create_collection("test", 128, DistanceMetric::Cosine)
605            .await
606            .unwrap();
607
608        let result = db
609            .create_collection("test", 128, DistanceMetric::Cosine)
610            .await;
611        assert!(matches!(result, Err(Error::CollectionExists(_))));
612    }
613}