#![warn(missing_docs)]
#![warn(clippy::all)]
pub mod collection;
pub mod config;
pub mod distance;
pub mod error;
pub mod index;
pub mod persistence;
pub mod types;
pub use collection::Collection;
pub use config::Config;
pub use distance::DistanceMetric;
pub use error::{Error, Result};
pub use types::{SearchResult, VectorId, VectorMetadata};
use std::path::PathBuf;
use std::sync::Arc;
use tracing::{debug, info, instrument, warn};
#[derive(Clone)]
pub struct VectorDb {
inner: Arc<VectorDbInner>,
}
struct VectorDbInner {
config: Config,
collections: scc::HashMap<String, Arc<Collection>>,
}
impl VectorDb {
#[instrument(skip(config), fields(persistent = config.data_path.is_some()))]
pub async fn open(config: Config) -> Result<Self> {
info!("Opening vector database");
let db = Self {
inner: Arc::new(VectorDbInner {
config: config.clone(),
collections: scc::HashMap::new(),
}),
};
if let Some(ref path) = config.data_path {
db.load_collections(path).await?;
}
Ok(db)
}
#[instrument(skip(self))]
pub async fn create_collection(
&self,
name: &str,
dimensions: usize,
metric: DistanceMetric,
) -> Result<()> {
info!(name, dimensions, ?metric, "Creating collection");
if self.inner.collections.contains(name) {
return Err(Error::CollectionExists(name.to_string()));
}
let collection = Collection::new(
name.to_string(),
dimensions,
metric,
self.inner.config.hnsw_config.clone(),
)?;
if self.inner.collections.insert(name.to_string(), Arc::new(collection)).is_err() {
return Err(Error::CollectionExists(name.to_string()));
}
if let Some(ref path) = self.inner.config.data_path {
self.persist_collection_metadata(path, name).await?;
}
Ok(())
}
#[instrument(skip(self))]
pub async fn delete_collection(&self, name: &str) -> Result<()> {
info!(name, "Deleting collection");
if self.inner.collections.remove(name).is_none() {
return Err(Error::CollectionNotFound(name.to_string()));
}
if let Some(ref path) = self.inner.config.data_path {
self.delete_collection_files(path, name).await?;
}
Ok(())
}
pub fn collection_exists(&self, name: &str) -> bool {
self.inner.collections.contains(name)
}
pub fn list_collections(&self) -> Vec<String> {
let mut names = Vec::new();
self.inner.collections.scan(|k, _| {
names.push(k.clone());
});
names
}
pub fn get_collection(&self, name: &str) -> Result<Arc<Collection>> {
self.inner
.collections
.read(name, |_, v| v.clone())
.ok_or_else(|| Error::CollectionNotFound(name.to_string()))
}
#[instrument(skip(self, vector, metadata), fields(collection, id, dim = vector.len()))]
pub async fn insert(
&self,
collection: &str,
id: &str,
vector: &[f32],
metadata: Option<VectorMetadata>,
) -> Result<()> {
let col = self.get_collection(collection)?;
col.insert(id, vector, metadata)?;
debug!("Inserted vector");
Ok(())
}
#[instrument(skip(self, vectors), fields(collection))]
pub async fn insert_batch<'a, I>(&self, collection: &str, vectors: I) -> Result<usize>
where
I: IntoIterator<Item = (&'a str, &'a [f32], Option<VectorMetadata>)>,
{
let col = self.get_collection(collection)?;
let count = col.insert_batch(vectors)?;
debug!(count, "Inserted batch");
Ok(count)
}
#[instrument(skip(self, vector, metadata), fields(collection, id))]
pub async fn update(
&self,
collection: &str,
id: &str,
vector: &[f32],
metadata: Option<VectorMetadata>,
) -> Result<()> {
let col = self.get_collection(collection)?;
col.update(id, vector, metadata)?;
Ok(())
}
#[instrument(skip(self), fields(collection, id))]
pub async fn delete(&self, collection: &str, id: &str) -> Result<bool> {
let col = self.get_collection(collection)?;
let deleted = col.delete(id)?;
debug!(deleted, "Delete result");
Ok(deleted)
}
#[instrument(skip(self, ids), fields(collection, count = ids.len()))]
pub async fn delete_batch(&self, collection: &str, ids: &[&str]) -> Result<usize> {
let col = self.get_collection(collection)?;
let count = col.delete_batch(ids)?;
debug!(count, "Deleted batch");
Ok(count)
}
#[instrument(skip(self, query), fields(collection, limit, dim = query.len()))]
pub async fn search(
&self,
collection: &str,
query: &[f32],
limit: usize,
) -> Result<Vec<SearchResult>> {
let col = self.get_collection(collection)?;
let results = col.search(query, limit)?;
debug!(count = results.len(), "Search completed");
Ok(results)
}
#[instrument(skip(self, query), fields(collection, limit, min_score))]
pub async fn search_with_threshold(
&self,
collection: &str,
query: &[f32],
limit: usize,
min_score: f32,
) -> Result<Vec<SearchResult>> {
let col = self.get_collection(collection)?;
let results = col.search_with_threshold(query, limit, min_score)?;
Ok(results)
}
pub async fn get(&self, collection: &str, id: &str) -> Result<Option<(Vec<f32>, Option<VectorMetadata>)>> {
let col = self.get_collection(collection)?;
Ok(col.get(id))
}
pub fn contains(&self, collection: &str, id: &str) -> Result<bool> {
let col = self.get_collection(collection)?;
Ok(col.contains(id))
}
pub fn count(&self, collection: &str) -> Result<usize> {
let col = self.get_collection(collection)?;
Ok(col.len())
}
pub fn collection_stats(&self, collection: &str) -> Result<CollectionStats> {
let col = self.get_collection(collection)?;
Ok(col.stats())
}
#[instrument(skip(self))]
pub async fn persist(&self) -> Result<()> {
let Some(ref path) = self.inner.config.data_path else {
debug!("Skipping persist for in-memory database");
return Ok(());
};
info!("Persisting database to disk");
let mut to_persist: Vec<(String, Arc<Collection>)> = Vec::new();
self.inner.collections.scan(|name, collection| {
to_persist.push((name.clone(), collection.clone()));
});
for (name, collection) in to_persist {
self.persist_collection(path, &name, &collection).await?;
}
Ok(())
}
#[instrument(skip(self))]
pub async fn compact(&self, collection: &str) -> Result<()> {
let col = self.get_collection(collection)?;
col.compact()?;
Ok(())
}
async fn load_collections(&self, path: &PathBuf) -> Result<()> {
if !path.exists() {
tokio::fs::create_dir_all(path).await?;
return Ok(());
}
let metadata_path = path.join("collections.json");
if !metadata_path.exists() {
return Ok(());
}
let data = tokio::fs::read_to_string(&metadata_path).await?;
let collection_names: Vec<String> = serde_json::from_str(&data)
.map_err(|e| Error::Persistence(format!("Failed to parse collections.json: {}", e)))?;
for name in collection_names {
match self.load_collection(path, &name).await {
Ok(collection) => {
let _ = self.inner.collections.insert(name.clone(), Arc::new(collection));
info!(name, "Loaded collection");
}
Err(e) => {
warn!(name, error = %e, "Failed to load collection, skipping");
}
}
}
Ok(())
}
async fn load_collection(&self, base_path: &PathBuf, name: &str) -> Result<Collection> {
persistence::load_collection(base_path, name).await
}
async fn persist_collection(
&self,
base_path: &PathBuf,
name: &str,
collection: &Collection,
) -> Result<()> {
persistence::save_collection(base_path, name, collection).await
}
async fn persist_collection_metadata(&self, base_path: &PathBuf, _name: &str) -> Result<()> {
let collections = self.list_collections();
let metadata_path = base_path.join("collections.json");
let data = serde_json::to_string_pretty(&collections)
.map_err(|e| Error::Persistence(format!("Failed to serialize collections: {}", e)))?;
tokio::fs::write(&metadata_path, data).await?;
Ok(())
}
async fn delete_collection_files(&self, base_path: &PathBuf, name: &str) -> Result<()> {
let collection_path = base_path.join(name);
if collection_path.exists() {
tokio::fs::remove_dir_all(&collection_path).await?;
}
self.persist_collection_metadata(base_path, name).await?;
Ok(())
}
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CollectionStats {
pub name: String,
pub vector_count: usize,
pub dimensions: usize,
pub metric: DistanceMetric,
pub memory_bytes: usize,
pub hnsw_params: HnswParams,
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct HnswParams {
pub m: usize,
pub ef_construction: usize,
pub ef_search: usize,
}
use serde_json;
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_create_and_search() {
let db = VectorDb::open(Config::memory()).await.unwrap();
db.create_collection("test", 3, DistanceMetric::Cosine)
.await
.unwrap();
db.insert("test", "vec1", &[1.0, 0.0, 0.0], None)
.await
.unwrap();
db.insert("test", "vec2", &[0.0, 1.0, 0.0], None)
.await
.unwrap();
db.insert("test", "vec3", &[0.9, 0.1, 0.0], None)
.await
.unwrap();
let results = db.search("test", &[1.0, 0.0, 0.0], 10).await.unwrap();
assert!(!results.is_empty());
assert_eq!(results[0].id, "vec1");
}
#[tokio::test]
async fn test_collection_lifecycle() {
let db = VectorDb::open(Config::memory()).await.unwrap();
assert!(!db.collection_exists("test"));
db.create_collection("test", 128, DistanceMetric::Euclidean)
.await
.unwrap();
assert!(db.collection_exists("test"));
db.delete_collection("test").await.unwrap();
assert!(!db.collection_exists("test"));
}
#[tokio::test]
async fn test_duplicate_collection_error() {
let db = VectorDb::open(Config::memory()).await.unwrap();
db.create_collection("test", 128, DistanceMetric::Cosine)
.await
.unwrap();
let result = db
.create_collection("test", 128, DistanceMetric::Cosine)
.await;
assert!(matches!(result, Err(Error::CollectionExists(_))));
}
}