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::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#[derive(Clone)]
95pub struct VectorDb {
96 inner: Arc<VectorDbInner>,
97}
98
99struct VectorDbInner {
100 config: Config,
101 collections: scc::HashMap<String, Arc<Collection>>,
103}
104
105impl VectorDb {
106 #[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 if let Some(ref path) = config.data_path {
134 db.load_collections(path).await?;
135 }
136
137 Ok(db)
138 }
139
140 #[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 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 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 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 #[instrument(skip(self))]
200 pub async fn delete_collection(&self, name: &str) -> Result<()> {
201 info!(name, "Deleting collection");
202
203 if self.inner.collections.remove(name).is_none() {
205 return Err(Error::CollectionNotFound(name.to_string()));
206 }
207
208 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 pub fn collection_exists(&self, name: &str) -> bool {
218 self.inner.collections.contains(name)
219 }
220
221 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 pub fn count(&self, collection: &str) -> Result<usize> {
412 let col = self.get_collection(collection)?;
413 Ok(col.len())
414 }
415
416 pub fn collection_stats(&self, collection: &str) -> Result<CollectionStats> {
418 let col = self.get_collection(collection)?;
419 Ok(col.stats())
420 }
421
422 #[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 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 #[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 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 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 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 self.persist_collection_metadata(base_path, name).await?;
523 Ok(())
524 }
525}
526
527#[derive(Debug, Clone)]
529#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
530pub struct CollectionStats {
531 pub name: String,
533 pub vector_count: usize,
535 pub dimensions: usize,
537 pub metric: DistanceMetric,
539 pub memory_bytes: usize,
541 pub hnsw_params: HnswParams,
543}
544
545#[derive(Debug, Clone)]
547#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
548pub struct HnswParams {
549 pub m: usize,
551 pub ef_construction: usize,
553 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}