1#![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
72pub use collection::Collection;
74pub use config::Config;
75pub use distance::{
76 DistanceMetric, cosine_similarity, dot_product, l2_distance, normalize_vector,
77 validate_dimensions,
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#[derive(Clone)]
98pub struct VectorDb {
99 inner: Arc<VectorDbInner>,
100}
101
102struct VectorDbInner {
103 config: Config,
104 collections: scc::HashMap<String, Arc<Collection>>,
106}
107
108impl VectorDb {
109 #[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 if let Some(ref path) = config.data_path {
137 db.load_collections(path).await?;
138 }
139
140 Ok(db)
141 }
142
143 #[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 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 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 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 #[instrument(skip(self))]
203 pub async fn delete_collection(&self, name: &str) -> Result<()> {
204 info!(name, "Deleting collection");
205
206 if self.inner.collections.remove(name).is_none() {
208 return Err(Error::CollectionNotFound(name.to_string()));
209 }
210
211 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 pub fn collection_exists(&self, name: &str) -> bool {
221 self.inner.collections.contains(name)
222 }
223
224 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 pub fn count(&self, collection: &str) -> Result<usize> {
415 let col = self.get_collection(collection)?;
416 Ok(col.len())
417 }
418
419 pub fn collection_stats(&self, collection: &str) -> Result<CollectionStats> {
421 let col = self.get_collection(collection)?;
422 Ok(col.stats())
423 }
424
425 #[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 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 #[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 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 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 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 self.persist_collection_metadata(base_path, name).await?;
526 Ok(())
527 }
528}
529
530#[derive(Debug, Clone)]
532#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
533pub struct CollectionStats {
534 pub name: String,
536 pub vector_count: usize,
538 pub dimensions: usize,
540 pub metric: DistanceMetric,
542 pub memory_bytes: usize,
544 pub hnsw_params: HnswParams,
546}
547
548#[derive(Debug, Clone)]
550#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
551pub struct HnswParams {
552 pub m: usize,
554 pub ef_construction: usize,
556 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}