moonseek

    Embedded full-text search engine: inverted index, BM25, Chinese/English tokenization, fuzzy search (BK-tree), did-you-mean, server-side highlighting, faceted filtering, score explanation, segmented index with WAL crash recovery. Runs on native/WASM/JS.

    search
    full-text
    index
    bm25
    chinese
    wasm
    fuzzy
    highlight
    wal
    Download zip
    Version
    0.3.0
    License
    Apache-2.0
    Last updated
    2 days ago
    Downloads
    17

    #moonseek

    Embedded full-text search engine in pure MoonBit. Inverted index, BM25 ranking, dictionary-free Chinese tokenization, fuzzy search, faceted filtering, server-side highlighting, crash-safe WAL — runs on native, WebAssembly and JavaScript.

    纯 MoonBit 实现的嵌入式全文搜索引擎:倒排索引、BM25、免词典中文分词、模糊搜索、分面过滤、服务端高亮、WAL 崩溃恢复,支持 native / WASM / JS 三端。

    CI License

    #Why moonseek

    MoonBit's ecosystem has HTTP servers, crypto and database drivers — but no tantivy/Lucene-class embedded search engine. moonseek fills that gap with a single dependency-light library that works everywhere MoonBit compiles, including inside the browser via WasmGC.

    #Features

    • Inverted index with per-field weights (e.g. title ×3, body ×1)
    • BM25 ranking with configurable k1 / b
    • Chinese + English tokenization: Latin words with stop-word removal; CJK overlapping bigrams (Lucene CJKAnalyzer strategy) — no dictionary needed
    • Rich query syntax: term, "exact phrase", AND / OR / NOT, field:term, prefix*, parentheses, implicit AND
    • Fuzzy search: Levenshtein / Damerau-Levenshtein edit distance with early-exit bounded DP; BK-tree for sub-linear lookup (13–1780× faster than linear scan on a 24k-term vocabulary)
    • Did-you-mean: frequency-weighted spelling correction (suggest)
    • Faceted search: exact-match facet fields, AND/OR filters, per-facet value counts, offset pagination (search_faceted)
    • Ranking control: configurable sort (search_sorted), cursor pagination (search_after), per-term BM25 breakdown (explain)
    • Server-side highlighting: highlight / snippet with HTML escaping, CJK-aware codepoint spans, overlap merging, densest-window extraction
    • Stored fields: original texts kept in the index, retrievable via get_document / get_field, survive snapshots
    • Segmented index: immutable segments + tiered merge policy + cross-segment search with latest-version-wins (SegmentedIndex)
    • Write-ahead log: CRC-framed entries, torn-tail recovery, durable add + atomic checkpoint + crash-safe reopen (native)
    • Crash-safe persistence: versioned snapshot + CRC-32 checksum; atomic save (temp file → fsync → rename); torn/corrupt files are rejected, never silently loaded
    • Portable: pure MoonBit core (no FFI in the engine); native file store via moonbitlang/async; browser export via WasmGC + js-string builtins
    • Document lifecycle: add, replace (same id), delete

    #Quick start

    let index = @moonseek.Index::new([
    { name: "title", weight: 3.0 },
    { name: "body", weight: 1.0 },
    ])

    index.add({
    id: "doc1",
    fields: [
    ("title", "全文搜索引擎"),
    ("body", "倒排索引是搜索引擎的核心,BM25 负责排序。"),
    ],
    })
    index.add({
    id: "doc2",
    fields: [("title", "MoonBit"), ("body", "A fast language for WebAssembly")],
    })

    let hits = index.search("搜索引擎") // [{ id: "doc1", score: … }]
    let hits2 = index.search("title:moonbit") // field-scoped
    let hits3 = index.search("\"memory safety\" OR wasm*") // phrase + prefix

    // Persist (native)
    index.save("index.msk")
    let restored = @moonseek.Index::load("index.msk")

    // Or portable bytes (works on every backend)
    let image : Bytes = index.to_bytes()
    let restored2 = @moonseek.Index::from_bytes(image)

    #CLI

    moon run cmd/main -- index ./docs --index index.msk # index .txt/.md files moon run cmd/main -- search "搜索引擎" --index index.msk moon run cmd/main -- search "title:rust" --limit 5 moon run cmd/main -- info --index index.msk

    #Browser demo

    A complete search engine running inside your browser — no server, no network:

    moon build --target wasm-gc cp _build/wasm-gc/debug/build/web/web.wasm demo/web.wasm cd demo && python -m http.server 8000 # open http://localhost:8000 (Chrome / Edge with WasmGC + js-string builtins)

    The demo indexes 60 bilingual documents (MoonBit docs + Chinese classics + CS topics) in ~20 ms. Results use server-side highlighting (the WASM engine produces escaped HTML with CJK-aware <mark> spans), misspelled queries get did-you-mean suggestions and fuzzy fallback, and a live panel shows benchmark numbers and per-field term frequencies.

    #Performance

    moon bench --target native --release, 1000 synthetic documents (~80 tokens each), AMD Ryzen 7 7435H:

    Small corpus (moon bench, 1000 synthetic docs):

    OperationTime
    Index 1000 docs (with stored fields)~135 ms
    Term query (top-10)~2.4 ms
    Phrase query (top-10)~1.8 ms
    Snapshot save+load (with stored fields)~75 ms

    Stress test (bench/stress, 20,000 docs / 8.5 MB text / 23.8k terms, AMD Ryzen 7 7435H, release):

    OperationTime
    Index build~6.7 s (≈3,000 docs/s)
    Selective term query (df ≈ 300)~0.02 ms
    Prefix query~17 ms (dominated by scoring the matched terms)
    Saturated term (matches every doc)~13 ms
    Phrase query~18 ms
    Facet filter + aggregation (3k matches)~21 ms
    Fuzzy lookup, 24k termslinear ~100 ms → BK-tree 0.05–12 ms
    Snapshot 17 MB: serialize / load~2.4 s / ~1.7 s

    Browser (WasmGC, 60 bilingual docs): index ~25 ms, query 0.1–11 ms, snapshot 44 KB.

    #Architecture

    token.mbt Analyzer: Latin words + CJK bigrams, positions index.mbt Inverted index, field stats, BM25, stored fields query.mbt Lexer → recursive-descent parser → evaluator fuzzy.mbt Levenshtein/Damerau distance, fuzzy search suggest.mbt Frequency-weighted did-you-mean highlight.mbt Server-side highlight/spans/snippet (codepoint offsets) facet.mbt Facet values, filters, aggregations, pagination bktree.mbt BK-tree for sub-linear fuzzy lookup explain.mbt BM25 breakdown, sort orders, cursor pagination segment.mbt SegmentedIndex: immutable segments + tiered merge wal.mbt CRC-framed write-ahead log (portable byte layer) wal_native.mbt Durable add/checkpoint/crash recovery (native) codec.mbt Varint / UTF-8 / double / CRC-32 primitives snapshot.mbt MSK3 format: versioned payload + checksum + stored fields + facets store.mbt Native atomic file persistence (async/fs) web/ Browser exports (#export_name, js-string builtins) cmd/main/ CLI: index / search / info examples/ Runnable examples (basic, persistence) demo/ Single-page browser demo (60 docs, benchmarks, inspector)

    See docs/architecture.md for design details and the snapshot format specification.

    #Testing

    moon test # 217 tests (native), 203 (wasm-gc / js) moon test --target wasm-gc moon test --target js moon bench --release # benchmarks moon coverage analyze # coverage report moon run bench/stress --target native --release # 20k-doc stress benchmark

    Tests cover tokenization, boolean/phrase/prefix/fuzzy queries, BM25 ordering, spelling correction, highlighting spans and HTML escaping, segment merge correctness, WAL torn-tail recovery, snapshot roundtrips, corruption/truncation detection, crash-safe file persistence, and quickcheck properties (roundtrip, varint, positions, delete exclusion).

    #Roadmap

    #License

    Apache-2.0. Built for the MoonBit open-source ecosystem.

    CodecError

    pub(all) suberror CodecError {
    UnexpectedEof
    VarintOverflow
    InvalidUtf8
    BadMagic
    BadVersion(Int)
    CrcMismatch(UInt, UInt)
    } derive(Eq,
    Debug
    )

    Decoding errors (truncated or malformed data).

    CodecError::equal

    fn CodecError::equal(CodecError, CodecError) -> Bool

    CodecError::not_equal

    fn CodecError::not_equal(x : CodecError, y : CodecError) -> Bool

    QueryError

    pub(all) suberror QueryError {
    EmptyQuery
    UnterminatedPhrase
    UnexpectedToken(String)
    UnknownField(String)
    } derive(Eq,
    Debug
    )

    Query syntax errors.
    impl Show for QueryError

    QueryError::equal

    fn QueryError::equal(QueryError, QueryError) -> Bool

    QueryError::not_equal

    fn QueryError::not_equal(x : QueryError, y : QueryError) -> Bool

    QueryError::output

    fn QueryError::output(self : QueryError, logger : &Logger) -> Unit

    QueryError::to_string

    fn QueryError::to_string(self : QueryError) -> String

    StoreError

    pub(all) suberror StoreError {
    IoError(String)
    CorruptIndex(String)
    } derive(Eq,
    Debug
    )

    Errors from the store layer.
    impl Show for StoreError

    StoreError::equal

    fn StoreError::equal(StoreError, StoreError) -> Bool

    StoreError::not_equal

    fn StoreError::not_equal(x : StoreError, y : StoreError) -> Bool

    StoreError::output

    fn StoreError::output(self : StoreError, logger : &Logger) -> Unit

    StoreError::to_string

    fn StoreError::to_string(self : StoreError) -> String

    Analyzer

    pub(all) struct Analyzer {
    lowercase : Bool
    remove_stop_words : Bool
    cjk_bigram : Bool
    } derive(Eq,
    Debug
    )

    Text analyzer configuration.

    Analyzer::analyze

    fn Analyzer::analyze(self : Analyzer, text : String) -> Array[Token]

    Analyze text into a stream of tokens. Latin words are split on non-word characters; CJK runs become overlapping bigrams (single characters are emitted for runs of length 1).

    Analyzer::default

    fn Analyzer::default() -> Analyzer

    Analyzer::equal

    fn Analyzer::equal(Analyzer, Analyzer) -> Bool

    Analyzer::not_equal

    fn Analyzer::not_equal(x : Analyzer, y : Analyzer) -> Bool

    Analyzer::to_repr

    BkTree

    pub struct BkTree {
    // private fields
    }

    A BK-tree over a dictionary of terms.

    BkTree::from_terms

    fn BkTree::from_terms(terms : Array[String]) -> BkTree

    Build a BK-tree from an array of terms.

    BkTree::insert

    fn BkTree::insert(self : BkTree, term : String) -> Unit

    Insert a term. Duplicates are ignored.

    BkTree::len

    fn BkTree::len(self : BkTree) -> Int

    Number of terms in the tree.

    BkTree::new

    fn BkTree::new() -> BkTree

    BkTree::search

    fn BkTree::search(self : BkTree, query : String, max_distance? : Int) -> Array[FuzzyMatch]

    Find all terms within max_distance edits of query. Results are sorted by (distance, term).

    Bm25Params

    pub(all) struct Bm25Params {
    k1 : Double
    b : Double
    } derive(Eq,
    Debug
    )

    BM25 parameters (Robertson/Sparck Jones defaults).

    Bm25Params::default

    fn Bm25Params::default() -> Bm25Params

    Bm25Params::equal

    fn Bm25Params::equal(Bm25Params, Bm25Params) -> Bool

    Bm25Params::not_equal

    fn Bm25Params::not_equal(x : Bm25Params, y : Bm25Params) -> Bool

    Document

    pub(all) struct Document {
    id : String
    fields : Array[(String, String)]
    } derive(Eq,
    Debug
    )

    A document to be indexed. id is caller-assigned and must be unique within the index; re-adding an existing id replaces the old document.

    Document::equal

    fn Document::equal(Document, Document) -> Bool

    Document::not_equal

    fn Document::not_equal(x : Document, y : Document) -> Bool

    Document::to_repr

    Explanation

    pub(all) struct Explanation {
    id : String
    total_score : Double
    details : Array[ScoreDetail]
    } derive(Eq,
    Debug
    )

    Full explanation for one hit.

    Explanation::equal

    fn Explanation::equal(Explanation, Explanation) -> Bool

    Explanation::not_equal

    fn Explanation::not_equal(x : Explanation, y : Explanation) -> Bool

    FacetCount

    pub(all) struct FacetCount {
    value : String
    count : Int
    } derive(Eq,
    Debug
    )

    One facet value with its document count in a result set.

    FacetCount::equal

    fn FacetCount::equal(FacetCount, FacetCount) -> Bool

    FacetCount::not_equal

    fn FacetCount::not_equal(x : FacetCount, y : FacetCount) -> Bool

    FacetFilter

    pub(all) struct FacetFilter {
    field : String
    values : Array[String]
    } derive(Eq,
    Debug
    )

    A facet filter: field name + required values (OR within, AND across fields).

    FacetFilter::equal

    fn FacetFilter::equal(FacetFilter, FacetFilter) -> Bool

    FacetFilter::not_equal

    fn FacetFilter::not_equal(x : FacetFilter, y : FacetFilter) -> Bool

    FacetedResult

    pub(all) struct FacetedResult {
    hits : Array[Hit]
    total : Int
    facets : Array[(String, Array[FacetCount])]
    } derive(Eq,
    Debug
    )

    Search result with optional facet aggregations.

    FacetedResult::equal

    FacetedResult::not_equal

    fn FacetedResult::not_equal(x : FacetedResult, y : FacetedResult) -> Bool

    FieldSchema

    pub(all) struct FieldSchema {
    name : String
    weight : Double
    } derive(Eq,
    Debug
    )

    Field schema: name + scoring weight (e.g. title=3.0, body=1.0).

    FieldSchema::equal

    fn FieldSchema::equal(FieldSchema, FieldSchema) -> Bool

    FieldSchema::not_equal

    fn FieldSchema::not_equal(x : FieldSchema, y : FieldSchema) -> Bool

    FieldStats

    type FieldStats

    Per-field statistics needed by BM25.

    FuzzyMatch

    pub(all) struct FuzzyMatch {
    term : String
    distance : Int
    } derive(Eq,
    Debug
    )

    One dictionary term within the fuzzy distance bound.

    FuzzyMatch::equal

    fn FuzzyMatch::equal(FuzzyMatch, FuzzyMatch) -> Bool

    FuzzyMatch::not_equal

    fn FuzzyMatch::not_equal(x : FuzzyMatch, y : FuzzyMatch) -> Bool

    HighlightSpan

    pub(all) struct HighlightSpan {
    start : Int
    end : Int
    } derive(Eq,
    Debug
    )

    A half-open character range [start, end) in a stored field's original text. Offsets count Unicode codepoints: neither bytes nor UTF-16 code units.

    HighlightSpan::equal

    HighlightSpan::not_equal

    fn HighlightSpan::not_equal(x : HighlightSpan, y : HighlightSpan) -> Bool

    Hit

    pub(all) struct Hit {
    id : String
    score : Double
    } derive(Eq,
    Debug
    )

    One search hit.

    Hit::equal

    fn Hit::equal(Hit, Hit) -> Bool

    Hit::not_equal

    fn Hit::not_equal(x : Hit, y : Hit) -> Bool

    Hit::to_repr

    Index

    pub struct Index {
    schema : Array[FieldSchema]
    analyzer : Analyzer
    bm25 : Bm25Params
    postings :
    HashMap
    [String,
    HashMap
    [String, Array[Posting]]]
    doc_ids : Array[String]
    doc_nums :
    HashMap
    [String, Int]
    stats :
    HashMap
    [String, FieldStats]
    deleted :
    HashMap
    [Int, Unit]
    stored :
    HashMap
    [Int, Array[(String, String)]]
    facets :
    HashMap
    [Int, Array[(String, Array[String])]]
    terms_sorted :
    HashMap
    [String, Array[String]]
    bk_trees :
    HashMap
    [String, BkTree]
    }

    An in-memory inverted index over a fixed field schema.

    Index::add

    fn Index::add(self : Index, doc : Document) -> Unit

    Add or replace a document. Unknown field names abort.

    Index::analyzer

    fn Index::analyzer(self : Index) -> Analyzer

    The analyzer this index was created with.

    Index::bk_tree

    fn Index::bk_tree(self : Index, field? : String?) -> BkTree

    Build a BK-tree from the index's vocabulary (all fields or one field). The tree is cached inside the index and reused across calls until the next add; building one per query costs more than a linear scan for vocabularies under ~100k terms.

    Index::delete

    fn Index::delete(self : Index, id : String) -> Bool

    Delete a document by external id. Returns true if it existed.

    Index::doc_count

    fn Index::doc_count(self : Index) -> Int

    Number of live documents.

    Index::doc_freq

    fn Index::doc_freq(self : Index, field : String, term : String) -> Int

    Document frequency of a term in a field (0 if absent).

    Index::doc_id

    fn Index::doc_id(self : Index, num : Int) -> String?

    Look up the external id of an internal doc number.

    Index::explain

    fn Index::explain(self : Index, query : String, id : String) -> Explanation? raise QueryError

    Explain the score of a query for a specific document. Returns None if the document doesn't match or doesn't exist.

    Index::from_bytes

    fn Index::from_bytes(data : Bytes) -> Index raise CodecError

    Restore an index from a byte image. Raises on bad magic, unknown version, truncation, or checksum mismatch.
    fn Index::fuzzy_search(self : Index, term : String, max_distance? : Int, limit? : Int) -> Array[Hit] raise QueryError

    Fuzzy search: expand term to dictionary terms within max_distance edits, evaluate each as a term query, and merge per-document scores by taking the maximum (a document matching several variants is not boosted for the repetition). Results are sorted by descending score, ties by id, and capped at limit (0 = unlimited), mirroring Index::search. Declared raise QueryError for API symmetry with Index::search; the current implementation never raises.

    Index::fuzzy_terms

    fn Index::fuzzy_terms(self : Index, term : String, max_distance? : Int, field? : String?) -> Array[FuzzyMatch]

    Find dictionary terms within max_distance edits of term, sorted by (distance, term). Distance is Damerau-Levenshtein (adjacent transpositions count as one edit, matching common typing errors). max_distance is clamped to [0, 2]. field restricts the vocabulary (None = all fields). Terms whose length differs by more than max_distance are skipped before any distance computation, so cost stays linear in vocabulary size.

    Index::fuzzy_terms_fast

    fn Index::fuzzy_terms_fast(self : Index, term : String, max_distance? : Int, field? : String?) -> Array[FuzzyMatch]

    Fast fuzzy term lookup using a BK-tree. Same semantics as fuzzy_terms but sub-linear for small distances on large vocabularies.

    Index::get_document

    fn Index::get_document(self : Index, id : String) -> Document?

    Retrieve the stored original document by external id. Returns None if the id is unknown or the document was deleted.

    Index::get_facets

    fn Index::get_facets(self : Index, id : String) -> Array[(String, Array[String])]

    Get facet values for a document.

    Index::get_field

    fn Index::get_field(self : Index, id : String, field : String) -> String?

    Retrieve one stored field's original text.

    Index::highlight

    fn Index::highlight(self : Index, id : String, field : String, query : String, pre_tag? : String, post_tag? : String) -> String raise QueryError

    Return the stored field text with pre_tag/post_tag around every highlight span. The source text is HTML-escaped (& < > " '); the tags themselves are not escaped. With no matches the escaped original is returned unchanged.

    Index::highlight_spans

    fn Index::highlight_spans(self : Index, id : String, field : String, query : String) -> Array[HighlightSpan] raise QueryError

    Compute highlight spans of query over the stored original text of one field. Latin terms match whole analyzed tokens (case handling follows the index analyzer); CJK bigram terms map back to their exact source ranges; phrases highlight the full adjacent run; prefixes highlight every whole token starting with the prefix. Overlapping ranges are merged and the result is sorted by start. Raises UnknownField for an unknown/deleted document or a field the document does not carry; query syntax errors propagate from parse_query.

    Index::load

    async fn Index::load(path : String) -> Index raise StoreError

    Load an index from path. Raises if the file is missing or corrupt.

    Index::load_or_create

    async fn Index::load_or_create(path : String, schema : Array[FieldSchema]) -> Index raise StoreError

    Load an index from path, or create a fresh one if the file does not exist. A corrupt file is still an error (never silently discarded).

    Index::new

    fn Index::new(schema : Array[FieldSchema], analyzer? : Analyzer, bm25? : Bm25Params) -> Index

    Create an empty index. Panics on duplicate field names.

    Index::postings_of

    fn Index::postings_of(self : Index, field : String, term : String) -> Array[Posting]

    Postings of a term in a field (empty if absent).

    Index::save

    async fn Index::save(self : Index, path : String) -> Unit raise StoreError

    Save the index to path atomically (write temp + fsync + rename).

    Index::schema

    fn Index::schema(self : Index) -> Array[FieldSchema]

    The field schema (names and weights), in declaration order.

    Index::search

    fn Index::search(self : Index, query : String, limit? : Int) -> Array[Hit] raise QueryError

    Search the index. limit caps the number of hits (0 = unlimited). Results are sorted by descending score, ties broken by document id.

    With a positive limit this is a bounded top-K selection: O(n · log K) comparisons instead of a full sort. On a 20k-doc corpus a common term (df ≈ 18k) went from ~140 ms (full sort with string tie-breaks) to a few milliseconds.

    Index::search_after

    fn Index::search_after(self : Index, query : String, after_score~ : Double, after_id~ : String, limit? : Int) -> Array[Hit] raise QueryError

    Cursor-based pagination: return hits after the given (score, id) cursor. More stable than offset pagination when documents are added/removed between pages. Pass the last hit's score and id from the previous page.

    Index::search_faceted

    fn Index::search_faceted(self : Index, query : String, options? : SearchOptions) -> FacetedResult raise QueryError

    Faceted search: query + filters + aggregations + pagination.

    Index::search_sorted

    fn Index::search_sorted(self : Index, query : String, limit? : Int, sort? : SortOrder) -> Array[Hit] raise QueryError

    Search with configurable sort order.

    Index::set_facets

    fn Index::set_facets(self : Index, id : String, facets : Array[(String, Array[String])]) -> Unit

    Set facet values for a document (replaces any previous values). The document must already exist in the index. Unknown fields are created on the fly (facets don't need schema declaration).

    Index::snippet

    fn Index::snippet(self : Index, id : String, field : String, query : String, max_chars? : Int, pre_tag? : String, post_tag? : String) -> String raise QueryError

    Extract a snippet of at most max_chars source characters: the window containing the most highlight spans (ties: earliest window), with the same tags and HTML escaping as highlight. Ellipses "…" mark truncation on either side. With no highlights the first max_chars characters are returned. max_chars <= 0 yields an empty string.

    Index::suggest

    fn Index::suggest(self : Index, query : String, max_distance? : Int) -> String?

    Did-you-mean spelling correction. For each bare word in the query that is absent from the dictionary but has a close match, return the query with the first such word corrected; all other text is preserved verbatim. Field-scoped terms (field:term), quoted phrases, operators (AND/OR/NOT), prefixes (foo*), and parentheses are left untouched. Candidates are ranked by document frequency so common words win over rare ones. Returns None when nothing is correctable. max_distance is clamped to [0, 2].

    Index::term_count

    fn Index::term_count(self : Index) -> Int

    Number of distinct terms across all fields.

    Index::terms_of

    fn Index::terms_of(self : Index, field : String) -> Array[String]

    All terms in a field, sorted in lexicographic (dictionary) order.

    Note: String::compare is SHORTLEX in MoonBit (compares lengths first), which scatters terms sharing a prefix across the array. Prefix queries need true lexicographic order to be contiguous, so this uses lexical_compare explicitly.

    The sorted list is cached and reused until the next add; callers must treat the returned array as read-only.

    Index::to_bytes

    fn Index::to_bytes(self : Index) -> Bytes

    Serialize the index to a portable byte image.

    Posting

    pub(all) struct Posting {
    doc : Int
    freq : Int
    positions : Array[Int]
    } derive(Eq,
    Debug
    )

    One posting: which document, how many times, and where.

    Posting::equal

    fn Posting::equal(Posting, Posting) -> Bool

    Posting::not_equal

    fn Posting::not_equal(x : Posting, y : Posting) -> Bool

    Posting::to_repr

    QToken

    Tokenize a query string into raw pieces: words, quoted phrases, operators (AND OR NOT), parentheses, and field prefixes.

    QToken::equal

    fn QToken::equal(QToken, QToken) -> Bool

    QToken::not_equal

    fn QToken::not_equal(x : QToken, y : QToken) -> Bool

    QToken::to_repr

    Query

    pub(all) enum Query {
    Term(String, String?)
    Phrase(Array[String], String?)
    Prefix(String, String?)
    And(Query, Query)
    Or(Query, Query)
    Not(Query, Query)
    MatchAll
    } derive(Eq,
    Debug
    )

    A parsed query node.

    Query::equal

    fn Query::equal(Query, Query) -> Bool

    Query::not_equal

    fn Query::not_equal(x : Query, y : Query) -> Bool

    Query::to_repr

    Reader

    pub struct Reader {
    data : Bytes
    pos : Int
    }

    Cursor over a byte slice for decoding.

    Reader::new

    fn Reader::new(data : Bytes) -> Reader

    Reader::read_byte

    fn Reader::read_byte(self : Reader) -> Byte raise CodecError

    Reader::read_double

    fn Reader::read_double(self : Reader) -> Double raise CodecError

    Reader::read_string

    fn Reader::read_string(self : Reader) -> String raise CodecError

    Reader::read_u32_le

    fn Reader::read_u32_le(self : Reader) -> UInt raise CodecError

    Reader::read_varint

    fn Reader::read_varint(self : Reader) -> Int raise CodecError

    Reader::remaining

    fn Reader::remaining(self : Reader) -> Int

    ScoreDetail

    pub(all) struct ScoreDetail {
    field : String
    term : String
    tf : Int
    df : Int
    idf : Double
    norm : Double
    score : Double
    } derive(Eq,
    Debug
    )

    One term's contribution to a document's score.

    ScoreDetail::equal

    fn ScoreDetail::equal(ScoreDetail, ScoreDetail) -> Bool

    ScoreDetail::not_equal

    fn ScoreDetail::not_equal(x : ScoreDetail, y : ScoreDetail) -> Bool

    SearchOptions

    pub(all) struct SearchOptions {
    limit : Int
    offset : Int
    filters : Array[FacetFilter]
    facet_fields : Array[String]
    } derive(Eq,
    Debug
    )

    Search options extending the basic query with facets and pagination.

    SearchOptions::default

    fn SearchOptions::default() -> SearchOptions

    SearchOptions::equal

    SearchOptions::not_equal

    fn SearchOptions::not_equal(x : SearchOptions, y : SearchOptions) -> Bool

    SegmentedIndex

    pub struct SegmentedIndex {
    schema : Array[FieldSchema]
    analyzer : Analyzer
    bm25 : Bm25Params
    segments : Array[Index]
    active : Index
    segment_max_docs : Int
    }

    A multi-segment full-text index.

    SegmentedIndex::add

    fn SegmentedIndex::add(self : SegmentedIndex, doc : Document) -> Unit

    Add or replace a document in the active segment. Freezes the active segment once it reaches segment_max_docs live documents. Re-adding an id tombstones its older versions in frozen segments so that position-based readers (get_document) agree with search's newest-wins resolution even before a merge compacts the stack.

    SegmentedIndex::add_durable

    async fn SegmentedIndex::add_durable(self : SegmentedIndex, dir : String, doc : Document) -> Unit raise StoreError

    Append an Add entry to dir/wal.log (fsync) and then apply it in memory. dir must be the same directory passed to open_or_create.

    SegmentedIndex::checkpoint

    async fn SegmentedIndex::checkpoint(self : SegmentedIndex, dir : String) -> Unit raise StoreError

    Atomically persist the full index state and clear the WAL. Write temp + fsync + rename, then truncate the log.

    SegmentedIndex::delete

    fn SegmentedIndex::delete(self : SegmentedIndex, id : String) -> Bool

    Mark a document deleted in every segment (all versions of the id). Returns true if the id existed, matching Index::delete semantics (an already-deleted id still "exists" as a tombstone).

    SegmentedIndex::delete_durable

    async fn SegmentedIndex::delete_durable(self : SegmentedIndex, dir : String, id : String) -> Bool raise StoreError

    Append a Delete entry to dir/wal.log (fsync) and then apply it in memory. Returns true if the id existed (same semantics as delete).

    SegmentedIndex::doc_count

    fn SegmentedIndex::doc_count(self : SegmentedIndex) -> Int

    Number of distinct live documents (newest version per id wins).

    SegmentedIndex::flush

    fn SegmentedIndex::flush(self : SegmentedIndex) -> Unit

    Freeze the active segment into the immutable stack (no-op if empty).

    SegmentedIndex::from_bytes

    fn SegmentedIndex::from_bytes(data : Bytes) -> SegmentedIndex raise CodecError

    Restore a segmented index from a byte image. Raises on bad magic, unknown version, truncation, or checksum mismatch.

    SegmentedIndex::get_document

    fn SegmentedIndex::get_document(self : SegmentedIndex, id : String) -> Document?

    Retrieve the newest live version of a document by external id.

    SegmentedIndex::get_field

    fn SegmentedIndex::get_field(self : SegmentedIndex, id : String, field : String) -> String?

    Retrieve one stored field's text from the newest live version.

    SegmentedIndex::merge

    fn SegmentedIndex::merge(self : SegmentedIndex, max_segments? : Int) -> Unit

    Tiered merge policy. Segments are bucketed by size class (floor(log2(live docs))). While the total segment count exceeds max_segments, the most populated tier is collapsed into a single rebuilt segment; ties go to the smallest tier so tiny segments are swept up first (classic tiered/"log-structured" behavior). The active segment participates so a merge also folds in recent writes. Rebuild replays the newest live version of every document through Index::add, which drops deleted docs and reassigns doc numbers.

    SegmentedIndex::new

    fn SegmentedIndex::new(schema : Array[FieldSchema], segment_max_docs? : Int) -> SegmentedIndex

    Create an empty segmented index. segment_max_docs is clamped to >= 1.

    SegmentedIndex::open_or_create

    async fn SegmentedIndex::open_or_create(dir : String, schema : Array[FieldSchema]) -> SegmentedIndex raise StoreError

    Open the index stored in dir, or create a fresh one. Replays the WAL on top of the last checkpoint. The directory is created if missing.

    SegmentedIndex::search

    fn SegmentedIndex::search(self : SegmentedIndex, query : String, limit? : Int) -> Array[Hit] raise QueryError

    Search every segment and merge the hits.

    Newest-wins resolution: each segment is queried normally, then every hit is resolved against the newest live version of its id. A hit for a deleted id is dropped; a hit for a stale version is re-scored by evaluating the same parsed query against a one-document index built from the newest version. This guarantees update semantics identical to a single index: terms that only existed in the old version stop matching, and scores always reflect the newest content.

    Scoring across segments: each segment computes BM25 with its own local IDF/avgdl, so raw scores are NOT directly comparable. We normalize per segment by dividing each hit score by that segment's maximum score for the query (max-score normalization to [0, 1]). This is the standard federated-search approximation: it preserves within-segment ranking exactly and makes cross-segment ordering depend on relative, not absolute, relevance. Ties (including all MatchAll hits, which score 1.0 everywhere) are broken by document id, ascending, for determinism.

    SegmentedIndex::segment_count

    fn SegmentedIndex::segment_count(self : SegmentedIndex) -> Int

    Number of segments: frozen (immutable) ones plus the active segment if it holds any documents. An empty active segment is not counted.

    SegmentedIndex::to_bytes

    fn SegmentedIndex::to_bytes(self : SegmentedIndex) -> Bytes

    Serialize: magic "MSKS" | payload | crc32(payload) u32le. Payload: version | segment_max_docs | schema | analyzer/bm25 config | immutable segment count | each segment as length-prefixed MSK2 image | active segment as length-prefixed MSK2 image.

    SortOrder

    pub(all) enum SortOrder {
    ScoreDesc
    ScoreAsc
    IdAsc
    IdDesc
    } derive(Eq,
    Debug
    )

    Sort order for search results.

    SortOrder::equal

    fn SortOrder::equal(SortOrder, SortOrder) -> Bool

    SortOrder::not_equal

    fn SortOrder::not_equal(x : SortOrder, y : SortOrder) -> Bool

    Token

    pub(all) struct Token {
    term : String
    position : Int
    } derive(Eq,
    Debug
    )

    A token emitted by the analyzer: the normalized term plus its position in the token stream (used for phrase queries).

    Token::equal

    fn Token::equal(Token, Token) -> Bool

    Token::not_equal

    fn Token::not_equal(x : Token, y : Token) -> Bool

    Token::to_repr

    WalEntry

    pub(all) enum WalEntry {
    Add(Document)
    Delete(String)
    } derive(Eq,
    Debug
    )

    One durable mutation.

    WalEntry::equal

    fn WalEntry::equal(WalEntry, WalEntry) -> Bool

    WalEntry::not_equal

    fn WalEntry::not_equal(x : WalEntry, y : WalEntry) -> Bool

    WalEntry::to_repr

    crc32

    fn crc32(data : Bytes) -> UInt

    CRC-32 (IEEE) of a byte slice.

    damerau_levenshtein

    fn damerau_levenshtein(a : String, b : String) -> Int

    Damerau-Levenshtein distance (optimal string alignment variant): like Levenshtein, but an adjacent transposition costs one edit. Rolling 3-row DP: O(m*n) time, O(min(m,n)) space. The OSA restriction (no substring edited more than once) matches the common "typo distance" use case.

    damerau_levenshtein_bounded

    fn damerau_levenshtein_bounded(a : String, b : String, bound : Int) -> Int

    Damerau-Levenshtein distance with an early exit: returns bound + 1 as soon as no cell in the current row can lead to a distance <= bound. This is what makes fuzzy matching over large vocabularies fast — the full-matrix version allocated m*n cells per candidate.

    explain_terms

    fn explain_terms(index : Index, query : Query) -> Array[String]

    Terms the evaluator actually scores for a query, matching eval: Phrase contributes its first term only (phrase frequency is folded in), Prefix expands to the matching dictionary terms, Not contributes only its left branch.

    levenshtein

    fn levenshtein(a : String, b : String) -> Int

    Levenshtein edit distance between two strings, counting insertions, deletions and substitutions. Operates on Unicode code points (Chars), so CJK and astral-plane characters each count as one character. Classic DP with a single row: O(m*n) time, O(min(m,n)) space.

    parse_query

    fn parse_query(input : String, analyzer? : Analyzer, fields? : Array[String]) -> Query raise QueryError

    Parse a query string against the index's schema.

    query_terms

    fn query_terms(query : Query) -> Array[String]

    Collect the highlightable terms of a query AST: every Term and Phrase word, plus the prefix itself for Prefix nodes. The right branch of Not and MatchAll contribute nothing (only positive matches are highlighted). Results are deduplicated in first-occurrence order.

    tokenize

    fn tokenize(text : String) -> Array[Token]

    Convenience: analyze with the default analyzer.

    wal_decode

    fn wal_decode(data : Bytes) -> Array[WalEntry] raise CodecError

    Decode a WAL image, replaying every complete entry. The "MWL1" header may appear at the start and again after any entry (each append batch to a fresh file carries one); a torn header tail is ignored. Stops silently at a torn or corrupt entry tail (crash recovery); raises only if the leading header is not a WAL, a mid-stream header is corrupt, or an entry type is unknown.

    wal_encode

    fn wal_encode(entries : Array[WalEntry]) -> Bytes

    Encode entries into a WAL image. A non-empty log starts with the "MWL1" header; an empty log is empty bytes (so appending the first entry to a fresh file also writes the header exactly once).

    write_double

    fn write_double(buf : Array[Byte], value : Double) -> Unit

    write_string

    fn write_string(buf : Array[Byte], s : String) -> Unit

    write_u32_le

    fn write_u32_le(buf : Array[Byte], value : UInt) -> Unit

    Append a little-endian uint32 (used for the trailing checksum).

    write_varint

    fn write_varint(buf : Array[Byte], value : Int) -> Unit

    Append an unsigned varint (LEB128) to the buffer. Every byte except the last has the continuation bit (0x80) set.