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::PathBuf;
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.inner.collections.insert(name.to_string(), Arc::new(collection)).is_err() {
174 return Err(Error::CollectionExists(name.to_string()));
175 }
176
177 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 #[instrument(skip(self))]
195 pub async fn delete_collection(&self, name: &str) -> Result<()> {
196 info!(name, "Deleting collection");
197
198 if self.inner.collections.remove(name).is_none() {
200 return Err(Error::CollectionNotFound(name.to_string()));
201 }
202
203 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 pub fn collection_exists(&self, name: &str) -> bool {
213 self.inner.collections.contains(name)
214 }
215
216 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 pub fn count(&self, collection: &str) -> Result<usize> {
403 let col = self.get_collection(collection)?;
404 Ok(col.len())
405 }
406
407 pub fn collection_stats(&self, collection: &str) -> Result<CollectionStats> {
409 let col = self.get_collection(collection)?;
410 Ok(col.stats())
411 }
412
413 #[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 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 #[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 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 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 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 self.persist_collection_metadata(base_path, name).await?;
511 Ok(())
512 }
513}
514
515#[derive(Debug, Clone)]
517#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
518pub struct CollectionStats {
519 pub name: String,
521 pub vector_count: usize,
523 pub dimensions: usize,
525 pub metric: DistanceMetric,
527 pub memory_bytes: usize,
529 pub hnsw_params: HnswParams,
531}
532
533#[derive(Debug, Clone)]
535#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
536pub struct HnswParams {
537 pub m: usize,
539 pub ef_construction: usize,
541 pub ef_search: usize,
543}
544
545use 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}