use crate::collection::Collection;
use crate::config::HnswConfig;
use crate::distance::DistanceMetric;
use crate::error::{Error, Result};
use crate::types::VectorMetadata;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tracing::{debug, info, warn};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct CollectionMetadata {
name: String,
dimensions: usize,
metric: String,
hnsw_m: usize,
hnsw_ef_construction: usize,
hnsw_ef_search: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct StoredVectorData {
id: String,
vector: Vec<f32>,
metadata: Option<VectorMetadata>,
}
pub async fn save_collection(
base_path: &PathBuf,
name: &str,
collection: &Collection,
) -> Result<()> {
let collection_path = base_path.join(name);
tokio::fs::create_dir_all(&collection_path).await?;
let metadata = CollectionMetadata {
name: name.to_string(),
dimensions: collection.dimensions(),
metric: collection.metric().name().to_string(),
hnsw_m: collection.hnsw_config().m,
hnsw_ef_construction: collection.hnsw_config().ef_construction,
hnsw_ef_search: collection.hnsw_config().ef_search,
};
let metadata_path = collection_path.join("metadata.json");
let metadata_json = serde_json::to_string_pretty(&metadata)
.map_err(|e| Error::Persistence(format!("Failed to serialize metadata: {}", e)))?;
tokio::fs::write(&metadata_path, metadata_json).await?;
let vectors_path = collection_path.join("vectors.json");
let vectors: Vec<StoredVectorData> = Vec::new();
let vectors_json = serde_json::to_string(&vectors)
.map_err(|e| Error::Persistence(format!("Failed to serialize vectors: {}", e)))?;
tokio::fs::write(&vectors_path, vectors_json).await?;
info!(name, path = ?collection_path, "Saved collection");
Ok(())
}
pub async fn load_collection(base_path: &PathBuf, name: &str) -> Result<Collection> {
let collection_path = base_path.join(name);
if !collection_path.exists() {
return Err(Error::CollectionNotFound(name.to_string()));
}
let metadata_path = collection_path.join("metadata.json");
let metadata_json = tokio::fs::read_to_string(&metadata_path).await?;
let metadata: CollectionMetadata = serde_json::from_str(&metadata_json)
.map_err(|e| Error::Persistence(format!("Failed to parse metadata: {}", e)))?;
let metric: DistanceMetric = metadata
.metric
.parse()
.map_err(|e: String| Error::Persistence(e))?;
let hnsw_config = HnswConfig {
m: metadata.hnsw_m,
m_max: metadata.hnsw_m * 2,
ef_construction: metadata.hnsw_ef_construction,
ef_search: metadata.hnsw_ef_search,
parallel_construction: true,
num_threads: 0,
};
let collection = Collection::new(
metadata.name.clone(),
metadata.dimensions,
metric,
hnsw_config,
)?;
let vectors_path = collection_path.join("vectors.json");
if vectors_path.exists() {
let vectors_json = tokio::fs::read_to_string(&vectors_path).await?;
let vectors: Vec<StoredVectorData> = serde_json::from_str(&vectors_json)
.map_err(|e| Error::Persistence(format!("Failed to parse vectors: {}", e)))?;
let count = vectors.len();
for stored in vectors {
if let Err(e) = collection.insert(&stored.id, &stored.vector, stored.metadata) {
warn!(id = stored.id, error = %e, "Failed to load vector");
}
}
debug!(name, count, "Loaded vectors");
}
info!(name, dimensions = metadata.dimensions, "Loaded collection");
Ok(collection)
}
#[cfg(feature = "serde")]
#[allow(dead_code)]
pub(crate) mod bincode_persistence {
use super::*;
pub(crate) async fn save_vectors_bincode(
path: &PathBuf,
vectors: &[StoredVectorData],
) -> Result<()> {
let data = bincode::serialize(vectors)
.map_err(|e| Error::Persistence(format!("Bincode serialize error: {}", e)))?;
let mut file = tokio::fs::File::create(path).await?;
file.write_all(&data).await?;
file.flush().await?;
Ok(())
}
pub(crate) async fn load_vectors_bincode(path: &PathBuf) -> Result<Vec<StoredVectorData>> {
let mut file = tokio::fs::File::open(path).await?;
let mut data = Vec::new();
file.read_to_end(&mut data).await?;
let vectors: Vec<StoredVectorData> = bincode::deserialize(&data)
.map_err(|e| Error::Persistence(format!("Bincode deserialize error: {}", e)))?;
Ok(vectors)
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[tokio::test]
async fn test_save_load_collection() {
let temp_dir = TempDir::new().unwrap();
let base_path = temp_dir.path().to_path_buf();
let collection = Collection::new(
"test".to_string(),
3,
DistanceMetric::Cosine,
HnswConfig::default(),
)
.unwrap();
collection.insert("vec1", &[1.0, 0.0, 0.0], None).unwrap();
save_collection(&base_path, "test", &collection)
.await
.unwrap();
let loaded = load_collection(&base_path, "test").await.unwrap();
assert_eq!(loaded.name(), "test");
assert_eq!(loaded.dimensions(), 3);
assert_eq!(loaded.metric(), DistanceMetric::Cosine);
}
}