mod memory; mod store; use crate::search::{analysis, retrieve::retrieve}; use crate::Kind; use std::collections::BTreeMap; pub use store::{IndexReader, IndexStore, IndexedDocument, Postings}; use crate::{Document, DocumentId, Query, SearchPage}; pub use memory::MemoryStore; pub type MemoryIndex = Engine; /// Port for a database-backed searchable index. Writes replace by stable ID. /// Implementations must make document, token and statistics changes atomic. /// Search requires all query terms, applies filters before paging and returns /// a deterministic order for an unchanged snapshot. Errors reach the caller. pub trait SearchIndex { type Error; fn upsert(&mut self, document: Document) -> Result<(), Self::Error>; fn remove(&mut self, id: DocumentId) -> Result; fn search(&self, query: &Query<'_>) -> Result; } #[derive(Default)] pub struct Engine { store: S, } impl Engine { pub fn new(store: S) -> Self { Self { store } } } impl SearchIndex for Engine { type Error = S::Error; fn upsert(&mut self, doc: Document) -> Result<(), Self::Error> { let title = analysis::normalize(&doc.title); let body = analysis::normalize(&doc.body); let mut short = analysis::index_tokens(&title); if doc.kind() != Kind::Post { short.push(doc.username.as_str().to_owned()); } let mut counts: BTreeMap = BTreeMap::new(); let mut lengths = [0; 2]; for (field, tokens) in [short, analysis::index_tokens(&body)] .into_iter() .enumerate() { lengths[field] = tokens.len(); for term in tokens { counts.entry(term).or_default()[field] += 1; } } self.store.replace(IndexedDocument { document: doc, title, body, lengths, frequencies: counts, }) } fn remove(&mut self, id: DocumentId) -> Result { self.store.delete(id) } fn search(&self, query: &Query) -> Result { retrieve(&self.store.snapshot()?, query) } }