/// A trigram inverted index over a small corpus — a user's notes, say /// (toki2's shape): [`build`] the documents, then [`search`] answers the /// ids of the documents containing a query, as a substring match on the /// [normalized](normalize) text. /// /// import search /// /// let idx = search.build [(1, "Toki Pona notes"), (2, "TODO: plant the toki pona stickers")] /// search.search idx "toki" // [1, 2] /// search.search idx "PONA" // [1, 2]: case-insensitive /// /// Indexing extracts the distinct trigrams (3-character windows) of each /// normalized document and posts the document's id to each trigram's list. /// A query's trigrams intersect those lists (roaring-style compressed /// bitmaps, `search/bitmap`) into candidates, and each candidate is /// verified with a real substring test, so a search answers exactly the /// documents containing the query — the trigrams only narrow the scan. /// /// Queries shorter than three characters have no trigram: they scan every /// document instead (fine for a per-user corpus). The index stores the /// normalized text of every document for verification: memory is the /// corpus's size on top of the postings. /// /// The index is a value: `add` and `remove` return a new one and leave the /// old as it was, so a process can keep one per user and swap it in. import bitmap import std/dict.{type Dict} import std/list import std/string /// A document's id, chosen by the caller; non-negative. Ids are the values /// of the postings' bitmaps, so dense small ids compress best. pub type DocId = Int /// An inverted index over a corpus of documents. Build one with [`build`], /// change it with [`add`] and [`remove`], query it with [`search`]. pub opaque type Index { Index( // The normalized text of each document, for verifying candidates. docs: Dict< DocId , String > // Each trigram's posting list: the documents containing it. , postings: Dict ) } /// The empty index. pub fn empty :: -> Index { Index(dict.empty (), dict.empty ()) } /// The number of documents. pub fn size :: idx: Index -> Int { dict.size idx.docs } pub fn is_empty :: idx: Index -> Bool { dict.is_empty idx.docs } /// The text compared and indexed: lowercase, without leading or trailing /// whitespace. pub fn normalize :: text: String -> String { string.trim (string.to_lower text) } /// The distinct trigrams (3-character windows) of `text`. pub fn trigrams :: text: String -> List { dict.keys (windows text 0 (string.length text) (dict.empty ())) } fn windows :: text: String i: Int n: Int acc: Dict -> Dict { if i + 3 <= n { windows text (i + 1) n (dict.insert acc (string.slice text i (i + 3)) ()) } else { acc } } /// An index of `docs`. A duplicate id keeps its last text. Panics on a /// negative id. pub fn build :: docs: List<(DocId, String)> -> Index { let (docs_dict, lists) = list.fold docs (dict.empty (), dict.empty ()) fn acc pair { let (d, lists) = acc let (id, text) = pair if id < 0 { panic "search.build: negative id {id}" } else { let text = normalize text (dict.insert d id text, collect (trigrams text) id lists) } } Index( docs: docs_dict , postings: dict.fold lists (dict.empty ()) fn acc t ids { dict.insert acc t (bitmap.from_list ids) } ) } /// `lists` with `id` prepended to each of `ts`' posting lists. fn collect :: ts: List id: DocId lists: Dict> -> Dict> { use lists, t <- list.fold ts lists let ids = match dict.get lists t { Some(ids) -> ids, None -> [] } dict.insert lists t [id, ..ids] } /// `idx` with `text` stored under `id`, replacing any text it had. Panics /// on a negative id. pub fn add :: idx: Index id: DocId text: String -> Index { let idx = remove idx id let text = normalize text let postings = { use postings, t <- list.fold (trigrams text) idx.postings let posting = match dict.get postings t { Some(posting) -> posting, None -> bitmap.empty () } dict.insert postings t (bitmap.add posting id) } Index(docs: dict.insert idx.docs id text, postings: postings) } /// `idx` without `id` (no change if it is absent). pub fn remove :: idx: Index id: DocId -> Index { match dict.get idx.docs id { None -> idx , Some(old) -> { let postings = { use postings, t <- list.fold (trigrams old) idx.postings match dict.get postings t { None -> postings , Some(posting) -> { let posting = bitmap.remove posting id if bitmap.is_empty posting { dict.remove postings t } else { dict.insert postings t posting } } } } Index(docs: dict.remove idx.docs id, postings: postings) } } } /// The ids of the documents containing `query`, ascending: a substring /// match on the normalized text. An empty query matches every document; /// one shorter than three characters scans every document. pub fn search :: idx: Index query: String -> List { let query = normalize query let n = string.length query if n == 0 { dict.keys idx.docs } else if n < 3 { scan idx query } else { match postings_of idx (trigrams query) [] { None -> [] , Some(postings) -> { let postings = list.sort_by postings fn a b { compare (bitmap.size a) (bitmap.size b) } use id <- list.filter (bitmap.to_list (intersect_all postings)) match dict.get idx.docs id { Some(text) -> string.contains text query, None -> False } } } } } /// Each trigram's posting list, or `None` when one has none (the query /// matches nothing). fn postings_of :: idx: Index ts: List acc: List -> Option> { match ts { [] -> Some(list.reverse acc) , [t, ..rest] -> match dict.get idx.postings t { Some(posting) -> postings_of idx rest [posting, ..acc], None -> None } } } fn intersect_all :: postings: List -> bitmap.Bitmap { match postings { [] -> bitmap.empty () , [first, ..rest] -> list.fold rest first bitmap.intersect } } /// The ids of the documents containing `query`: a scan, for queries too /// short for a trigram. fn scan :: idx: Index query: String -> List { list.reverse ( dict.fold idx.docs [] fn acc id text { if string.contains text query { [id, ..acc] } else { acc } } ) }