use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Document {
pub content: String,
pub metadata: HashMap<String, String>,
pub id: Option<String>,
}
impl Document {
pub fn new(content: impl Into<String>) -> Self {
Self {
content: content.into(),
metadata: HashMap::new(),
id: None,
}
}
pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.metadata.insert(key.into(), value.into());
self
}
pub fn with_id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
pub fn page_content(&self) -> &str {
&self.content
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VectorDocument {
pub document: Document,
pub embedding: Vec<f32>,
}
#[derive(Debug, Clone)]
pub struct SearchResult {
pub document: Document,
pub score: f32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkDocument {
pub chunk_id: String,
pub parent_id: String,
pub content: String,
pub segment: usize,
pub metadata: HashMap<String, String>,
}
impl ChunkDocument {
pub fn new(chunk_id: String, parent_id: String, content: String, segment: usize) -> Self {
Self {
chunk_id,
parent_id,
content,
segment,
metadata: HashMap::new(),
}
}
pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.metadata.insert(key.into(), value.into());
self
}
pub fn to_document(&self) -> Document {
Document {
content: self.content.clone(),
metadata: self.metadata.clone(),
id: Some(self.chunk_id.clone()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_document_creation() {
let doc = Document::new("Hello, world!")
.with_metadata("source", "test")
.with_id("doc-1");
assert_eq!(doc.content, "Hello, world!");
assert_eq!(doc.metadata.get("source"), Some(&"test".to_string()));
assert_eq!(doc.id, Some("doc-1".to_string()));
}
#[test]
fn test_document_page_content() {
let doc = Document::new("Test content");
assert_eq!(doc.page_content(), "Test content");
}
#[test]
fn test_chunk_document_to_document() {
let chunk = ChunkDocument::new("c1".to_string(), "p1".to_string(), "hello".to_string(), 0);
let doc = chunk.to_document();
assert_eq!(doc.content, "hello");
assert_eq!(doc.id, Some("c1".to_string()));
}
}