Skip to content

Latest commit

 

History

History
1185 lines (985 loc) · 69.8 KB

API_DOCUMENTATION.md

File metadata and controls

1185 lines (985 loc) · 69.8 KB

Otzaria Search Engine - API Documentation

This document describes the API exposed by the Otzaria Search Engine through Flutter/Dart bindings. The API is generated from Rust code using flutter_rust_bridge.

Table of Contents

  1. Classes
  2. Top-Level Functions
  1. Data Models

Classes

SearchEngine

Main search engine for full-text search with regex support.

Constructor

SearchEngine.new(String path)

Synchronous constructor that creates a new search engine instance.

Parameters:

  • path (String): File system path where the search index will be stored

Returns: SearchEngine instance


Methods

addDocument
Future<void> addDocument({
  required int ordinal,
  required String title,
  required String reference,
  required String topics,
  required String text,
  required BigInt segment,
  required bool isPdf,
  required String filePath,
  int? sectionOrdinal,
  List<String>? extraFacets,
})

Adds one line of a book to the search index.

Parameters:

  • ordinal (u32): The line's 0-based position in its book. The engine composes the document id as (bookNumber << 32) + ordinal + 1, where bookNumber is the number it gave the book (filePath) on its first write
  • title (String): Document title
  • reference (String): Document reference/citation
  • topics (String): Faceted topics (hierarchical, e.g., "category/subcategory")
  • text (String): Full document text to be indexed
  • segment (int/u64): Segment number within the document
  • isPdf (bool): Whether the document is a PDF
  • filePath (String): File path to the document
  • sectionOrdinal (u32?): The ordinal of the line that opens the line's section

Returns: Future


commit
Future<void> commit()

Commits all pending document additions to the index. Must be called after adding documents to make them searchable.

Returns: Future


search
Future<List<SearchResult>> search({
  required List<String> regexTerms,
  required List<String> facets,
  required int limit,
  required int offset,
  required int slop,
  required int maxExpansions,
  required ResultsOrder order,
  HighlightConfig? highlight,
})

Performs a search query on the index using regex patterns.

Parameters:

  • regexTerms (List): List of regex patterns to search for
    • Single term: matching index terms are materialized (capped at maxExpansions)
    • Multiple terms: uses RegexPhraseQuery with specified slop
  • facets (List): List of topic facets to filter by (empty list = no facet filter)
  • limit (int/u32): Maximum number of results to return
  • offset (int/u32): Number of leading results to skip (pagination)
  • slop (int/u32): Maximum distance between terms in phrase queries (for multi-term searches)
  • maxExpansions (int/u32): Regex-expansion ceiling. A single term truncates its term collection at the ceiling (partial results, flagged via the status-bearing variants). A multi-term phrase checks Tantivy's cumulative expansions independently in every segment: when every segment fits, the exact RegexPhraseQuery runs; otherwise the engine falls back to a term-list phrase built from per-position materialized term sets (per-position caps, truncation flagged) — never an error
  • order (ResultsOrder): Sort order for results (Catalogue or Relevance)
  • highlight (HighlightConfig?, optional): Snippet/highlight configuration; defaults to <font color=red> tags and 800 chars

Returns: Future<List>

Variants:

  • searchAndCount(...) → SearchPageResult — same arguments, returns the total hit count alongside the page in a single index pass
  • searchStream(..., chunkSize) → Stream<List<SearchResult>> — emits results in chunks as snippets are built
  • count(regexTerms, facets, slop, maxExpansions) → int — count only

Mode-specific search (exact / fuzzy / advanced)

Higher-level APIs that take a raw query string and build the query in Rust:

// Exact: term/phrase match after nikud-stripping + tokenization. Fastest.
Future<List<SearchResult>> searchExact({query, facets, limit, offset, order})

// Fuzzy: Levenshtein matching per token (maxDistance edits, 0–2).
Future<List<SearchResult>> searchFuzzy({query, facets, limit, offset, maxDistance, order})

// Advanced: Hebrew morphological query builder (prefixes, suffixes,
// full/deficient spelling, typo tolerance, alternative words, custom spacing).
Future<List<SearchResult>> searchAdvanced({
  query, facets, limit, offset, distance,
  customSpacing, alternativeWords, searchOptions, order,
  wordMatchMode, wordMatchCount, anyOrder,
})

wordMatchMode (optional, advanced family only) relaxes the all-words requirement: all (default — current behavior), anyWord, mostWords (n/2+1), or atLeast together with wordMatchCount (clamped to [1, n]). Any mode other than all drops the order/distance requirement: wordDistance scope behaves like sameParagraph, and sameSection requires the section to carry at least the required number of distinct query words. Duplicate query words count once toward the threshold. The negative query always requires all of its words.

anyOrder (optional, default false; advanced family plus generateHighlightPattern/generateIndexHighlightPattern) applies to the wordDistance scope with all words required: the words may appear in any order, each at its own position (a repeated query word needs two occurrences), all within one window of (n-1) * (distance + 1) positions — the span an ordered match may take, so every ordered match within a line is also an any-order match. It is ignored when customSpacing is set (per-pair spacing presumes an order), it applies to the negative query too, and an any-order match never continues onto the next line.

Each mode also provides count*, searchAndCount* and search*Stream variants (countExact, searchAndCountFuzzy, searchAdvancedStream, …). Queries are normalized like the index (nikud stripped, lowercased); empty queries return no results. Advanced-mode highlighting wraps every morphological variant that actually matched, not just the literal words; fuzzy-mode highlighting likewise wraps every term within the requested edit distance, not just exact occurrences of the query words.


User regex (/…/)

A query the user wraps in slashes is a regular expression (Rust regex syntax). The application classifies it first, synchronously, and falls back to its ordinary search when the result is invalid:

UserRegexPlan parseUserRegex({required String raw});          // sync, a few ms at most
UserRegexMatcher? prepareUserRegexMatcher({required String raw}); // sync; book view
List<HighlightMatch> UserRegexMatcher.findMatches({required String data}); // sync

final token = UserRegexCancellationToken();                    // token.cancel(), token.isCancelled
Stream<UserRegexStreamUpdate> searchUserRegexStream({raw, facets, limit, offset, order,
    chunkSize, required UserRegexCancellationToken cancellation});
Future<CountResult> countUserRegex({raw, facets, cancellation});
Future<BookCountResult> countByBookUserRegex({raw, facets, cancellation});
Future<FacetCountsResult> getFacetCountsUserRegex({raw, facets, facetPrefix, cancellation});

UserRegexPlan.kind:

Kind When How it is searched
invalid not wrapped, empty, bad syntax, longer than 300 characters, or too complex (reason) search the text as ordinary words
singleWord no explicit whitespace (/מש.ה/, /[א-ת]+ים/, /ספר.*/) against whole index terms, like an advanced regex word
wordSequence words split at the top level by a space or \s+ (/(משה|אהרן) רבנו/) an adjacent phrase of term patterns; continues onto the next line like any phrase
crossSpace anything else that spans a space (/שמע .* ישראל/, /(\S+\s){2}ישראל/, an inner \b), or ^/$ at an edge (/^ספר$/, /^שמע ישראל/) against each line's text

Rules shared by all kinds: the outer slashes and \b at the pattern's edges are dropped; case and nikud are ignored; geresh/gershayim (׳ ״ ‘ ’ “ ”) match their ASCII forms; maqaf is a space. Final letters stay distinct. . and negated classes never cross a space on their own — only explicit whitespace (a space, \s, \W, a class of spaces) makes a pattern crossSpace, as does a sequence word that names no letter (/שמע .* ישראל/). Term patterns match whole terms; in term patterns, wildcards cover Hebrew letters, Latin a-z, digits and quotes. A crossSpace match starts and ends on a word boundary when that edge of the pattern is a letter, and is matched against the line as the app's cleanLineForSearch sees it (tags removed, a breaking tag as a space, as is a <sup> or <sub> unless it wraps one letter inside a word; transparent inline tags and zero-width controls do not interrupt that context; nikud removed; maqaf/paseq/| as a space; whitespace collapsed), lowercased, quotes as ASCII. Footnote text stays in the line, as it does in the index. It never continues onto the next line.

Line anchors. ^ or $ at a pattern's edge (also (?m)^, (?m)$) is kept and makes the pattern crossSpace, even when it would be a term pattern without it: /^ספר$/ is a line whose whole text is ספר, /^שמע ישראל/ a line that begins with the phrase (it does not continue onto the next line), /^א.*/ a line that begins with א. ^ holds at the start of the line's text and also after a leading enumerator such as (ג) , [יא] or {פ} , and $ at its end and also before a trailing one such as {פ} or (א): — the enumerators a phrase skips when it continues across lines. An enumerator is up to 5 letters, digits or quotes in brackets, so a short word in parentheses at the line's edge (a citation such as (שם)) is skipped too. A […] enumerator is skipped only when a space separates it from the word: the index keeps [א]ויאמר as one word, so /^ויאמר/ does not match it. Only the matched words are highlighted, so /^ויאמר/ paints ויאמר in (ג) ויאמר, once: an anchor that holds past the enumerator is not also matched before it (/^\S+/ paints ויאמר, not (ג)); /^\(ג\) ויאמר/ matches the enumerator itself. $ does not skip anything else: punctuation (ויאמר:), a footnote marker or a footnote's text at the end of the line come before it. A pattern of anchors alone (/^$/), or with $ at its start or ^ at its end (/$א/), is invalid.

Cost. Term kinds cost what an advanced search costs; a pattern whose automaton would be large is relaxed (repetitions above 7 become unbounded, the exact pattern verifies every term) or refused at parse time. A crossSpace pattern reads candidate lines: when its fixed words (שמע, ישראל) narrow the scope to 5,000 lines or fewer they are read one by one; otherwise the books holding candidates are read, decoding only the candidate rows; a pattern with no selective fixed word reads every book in scope (the whole library takes on the order of 10–30 s) — so does an anchored pattern with no fixed word of 2 letters or more (/^א.*/). Results and progress stream as books are read, and the token stops it.

Stream events (UserRegexStreamUpdate). Term kinds send their counts first (totalCount, bookCounts, truncated), then results in chunks. A crossSpace search sends progress (progressDone/progressTotal — candidate lines, or books read; foundSoFar) and the requested page's results as soon as they are found, in catalogue order. The last event always has done: true and carries the final counts and truncated (and cancelled: true when the token stopped it). matchRanges[i] belongs to results[i]: for crossSpace, the UTF-16 ranges of the matches in the line's whole text (as getDocumentById returns it); empty for term kinds, whose snippets are painted and whose matches UserRegexMatcher finds in the book. truncated means partial: a term budget ran out, more than 100,000 lines matched, or lines could not be read (the library database suspended or busy). order applies to term kinds only; grouping is not offered.

Counts and facets of a crossSpace pattern run the same search; after a finished stream with the same pattern and facets they are answered from its cached result. A cancelled count or facet call fails with an error. facets filters as everywhere — the book's own topics path is a search in that book.

Book view. prepareUserRegexMatcher(raw).findMatches(line) finds every match in one displayed line (HTML and nikud included), in UTF-16 units, one word range per word of a sequence. An unanchored reader search can pass several lines as one unit. To treat ^ and $ as layout-line edges, pass each layout line separately.


Book numbers, order and stamps

Every book gets a book number from the engine on its first write, by filePath: the high half of all its document ids. A number is never given to another book of the same index (the highest one handed out is reserved in otzaria_book_numbers.json); a book rewritten in place keeps its number.

The catalogue and generation order are not in the ids. setBookOrder replaces the whole mapping (BookOrderEntry { filePath, catalogueOrder, generationOrder }), stored in otzaria_book_order.json beside the index, and ResultsOrder.catalogue / ResultsOrder.generation sort by it from the next call on — no reindexing. A book absent from the mapping sorts after every book in it, by number. The same mapping again changes nothing; every change bumps bookOrderRevision(). An engine that does not write (another window) picks up the books and the mapping another engine writes on its next sorted search. The first catalogue or generation search reads every book's number from the index; call warmBookOrder() after the window is shown so no search waits for it.

getBookStamps() returns per book: bookNumber, live documents, contentHash (computeBookFingerprint: text and metadata), textHash (computeContentFingerprint), metadataHash (computeBookMetadataFingerprint: title, topics, extra facets) and sourceHash (the sourceHash the book was written with, stored as given). A stamp is 0 when absent or when the book's documents disagree on it.

Write & maintenance API
Future<void> addDocumentsBatch({required List<DocumentInput> docs}) // bulk add, no commit
Future<BigInt> setBookOrder({required List<BookOrderEntry> entries}) // the order mapping
BigInt bookOrderRevision()
Future<void> warmBookOrder()                      // read numbers + build rank tables ahead
Future<List<BookStamps>> getBookStamps()          // number, documents and stamps per book
Future<void> upsertDocument({...})                // delete-by-id + re-insert, no commit
Future<void> upsertDocumentsBatch({required List<DocumentInput> docs})
Future<void> deleteDocumentById({required BigInt id})
Future<void> rollback()                           // discard writes since last commit
Future<void> optimize()                           // commit pending + merge all segments
Future<BigInt> getDocumentCount()
Future<int> getSegmentCount()
Future<List<FacetCount>> getFacetCounts({...})    // per-child facet counts for a prefix
Future<Map<String, int>> countByBook({...})       // per-filePath hit counts for a query

clear
Future<void> clear()

Removes all documents from the index.

Returns: Future


removeDocumentsByTitle
Future<void> removeDocumentsByTitle(String title)

Removes all documents with the specified title from the index.

Parameters:

  • title (String): Title of documents to remove

Returns: Future


countDocumentsByFilePath
Future<Map<String, int>> countDocumentsByFilePath()

Returns the number of live (committed, non-deleted) documents per distinct filePath across the whole index.

The result is read from the index itself rather than from any external state, so callers can reconstruct indexing progress directly from an index — e.g. after pointing the engine at a directory that already contains an index built elsewhere — and compare it against the current library to decide whether re-indexing is needed.

Returns: Future<Map<String, int>> - Map from filePath to its live document count


getIndexedFilePaths
Future<List<String>> getIndexedFilePaths()

Returns the distinct filePath values present in the index — i.e. which books have at least one live document. Convenience wrapper over countDocumentsByFilePath().

Returns: Future<List> - List of indexed file paths (unordered)


Line ranges

The lexical, user-regex, smart-lexical and semantic search/count/stream APIs accept an optional lineRanges argument. Omission or an empty list preserves the previous whole-book behavior. A nonempty list is an exclusive union of source ranges, intersected with the normal facets. It is applied before totals, book/facet counts, grouping, sorting and pagination; filtering an already returned page is not equivalent.

final selected = [
  BookLineRange(filePath: 'id:81', start: 120, end: 245),
  BookLineRange(filePath: 'db:another-library:81', start: 30, end: null),
];
// Pass the same selected list to every page and count of this search.

filePath is the exact indexed source identity, including the database/source prefix; a book title or a catalogue facet is not interchangeable with it. start is a zero-based text-line ordinal, inclusive. end is exclusive; null means through the end of the book. A client choosing a heading supplies the next heading at the same or a shallower level as end, so all nested headings remain included. Empty identities and reversed/empty intervals are rejected. Overlapping and adjacent ranges for the same source are normalized into one interval. This is a text-line selection; the application does not offer text headings for PDF page identities.

For supported cross-line searches both the anchor and continuation must be selected. The existing fuzzy path remains a single-line search. Same-section positive and negative prepasses are restricted to the selection too. Range identity participates in the regex cache and semantic session key, so changing it cannot continue an old page.

Semantic selection uses the current index and line source to plan eligible vector slots and their occurrence roles before top-k. The resolver does not trust stored record hints as the boundary: it recomputes anchors and inner windows and finds live copies and aliases inside the selected lines. A missing/failed plan, changed source or vector generation, cancellation, or an exceeded planning budget returns an explicit error, never unfiltered semantic candidates. Planning admits at most 200,000 live occurrence entries and 200,000 selected slot/role entries; cached plans share a combined 200,000-entry budget. A larger selection must be narrowed.

Existing semantic result limits still apply: at most 32 verified line occurrences per vector hit and the bounded candidate session (with its existing truncation indicators). A heading filter does not claim exhaustive semantic recall beyond those limits. The lexical path retains its existing count/completeness contract. No index schema or official artifact format changes are required by this filter. Generated bindings and the matching native library must be deployed together; official signed binary availability remains a separate release gate.

Semantic search
Future<SemanticVectorsInstallReport> installSemanticVectors({required SemanticVectorsInstallInput input, required SemanticCancellationToken cancellation})
Future<SemanticVectorsInfo> semanticVectorsInfo({required String vectorsDir})
Future<SemanticCompactionReport> compactSemanticVectors({required String vectorsDir, int? liveLibraryVersion, SemanticCompactionPolicy? policy, required SemanticCancellationToken cancellation})
Future<SemanticGenerationRetireReport> retirePreviousSemanticGeneration({required String vectorsDir})
Future<SemanticVectorsVerification> verifySemanticVectors({required String vectorsDir, required SemanticCancellationToken cancellation})
Future<SemanticCoverage> semanticCoverage({required String vectorsDir, required SemanticCancellationToken cancellation})
Future<SemanticCoveredBooks> semanticCoveredBooks({required String vectorsDir, required SemanticCancellationToken cancellation})
Future<SemanticStatus> openSemanticArtifact({required SemanticArtifactInput config})
Future<void> disableSemantic()
Future<SemanticStatus> semanticStatus()
Future<SemanticSearchResponse> searchSemantic({..., SemanticRankingOptions? ranking, List<SemanticVote>? votes, String? paginationSessionId, required SemanticCancellationToken cancellation})

// Development and testing: vectors built on this device.
Future<SemanticStatus> configureSemantic({required SemanticConfigInput config})
Future<SemanticIndexDiff> semanticIndexDiff()
Future<SemanticIndexingSummary> semanticIndexBooks({required List<SemanticBookInput> books})
Future<SemanticRemoveResult> removeSemanticBooks({required List<String> sourceBookKeys})
Future<SemanticResetResult> resetSemanticIndex()

Give each independent list its own paginationSessionId. Reuse that ID on continuation requests and pass the current votes to rank results still unseen. If the session expires, sessionRestarted signals that the returned page replaces the displayed list.

These reach the semantic sidecar only in a library built with a semantic feature; any other build reports an explicit notInBuild state and serves lexical results. The build hook builds the library with semantic, the ONNX backend, and ONNX is the only model format: GGUF models are not supported, and a model path that does not end in .onnx is refused by its name on every build, as a SemanticError of kind modelInvalid whose field is model_path. The README's "Semantic search integration" section covers the features, the release contract, the session lifecycle and the fallback contract. Every one of them but semanticStatus and disableSemantic throws a SemanticError when it fails (see "Failures and states" below).

The application never builds the library's vectors. The build machine embeds the library into a release of its vectors; the application installs it into a vector set with installSemanticVectors, opens the set with openSemanticArtifact, and embeds only the query. configureSemantic and the calls below it build vectors on the device, for development and testing, and are not for the library.

installSemanticVectors installs a release into the vector set at vectorsDir, creating the set when there is none: a base replaces whatever the set holds, and a delta brings it from the library version it stands at to the next. The set is locked throughout and the new generation goes live in one flip, so a release refused, cancelled or cut off by a crash leaves the set as it was; an open session on the same set is moved onto the new generation before the call returns. One install or compaction of a set runs at a time. A second one in this process is refused at once; otherwise the call waits up to a second for the set's lock before it is refused. Either refusal is vectorsBusy with field vectors_dir: the set is as it was and an open session keeps serving; try again once the other has finished.

field meaning
vectorsDir the vector set, <root>/vectors
segmentPath the release's segment as downloaded: .oxv, or .oxv.zst compressed with zstd, which is expanded into a file of the install's own in the set's incoming/ folder first, gone when the call returns. A segment inside incoming/ is moved into the set when the install succeeds, and stays where it is when it fails (on Windows a read-only one is copied instead); anywhere else it is copied and left
manifestJson the release manifest published beside the segment (release.json), as published
publishedManifestSha256 optional: the manifest's SHA-256 as the release publishes it outside the manifest; without it an install detects damage and the wrong release, not one rebuilt to match
modelIdentityJson the model identity this installation queries with, as for opening: a release it would not open is not installed

A release manifest's requires (indexSchemaVersion, lineTextVersion, keyVersion) and builtBy are information, and nothing checks them: the release's identity is what an install and an open check. The published v30 release says indexSchemaVersion: 5, the schema whose chunkKey column its records are resolved by, and installs, opens and searches on an index without a column this build uses all the same, with the limits below.

The report says what the release was (kind: base, delta or compacted), the library version and generation the set stands at, the vectors it added and the older ones it deleted, the set's size, and whether it wants compacting. alreadyApplied is a delta the set already stood at or past; a base always replaces the set.

semanticVectorsInfo reads what is installed from the set's small files, with nothing opened or cleaned up: present: false when nothing is, and otherwise its identity digest, library version and release tag, generation, segments, live and dead vectors, size, needsCompaction, and recoveredFromPrevious when the live generation did not open and the one before it was opened instead.

compactSemanticVectors merges the set into one segment when its SemanticCompactionPolicy asks for it (more than maxSegments segments, deltas past maxDeltaRatio of the base, dead vectors past maxDeadRatio, or force); const SemanticCompactionPolicy() and SemanticCompactionPolicy.defaults() are the sidecar's defaults, and passing none is passing them. liveLibraryVersion is the library version the open index holds, which the application knows: when it is the set's own and the index has the chunkKey column, every record moves onto the line that holds its text now (hintsRefreshed) and records whose book no longer holds it are dropped (recordsPruned). A compaction refuses to start without minFreeSpaceFactor times its output's size free, as insufficientDiskSpace, and a threshold out of range is invalidInput whose field is policy.<option>. Locked, crash-safe and cancellable as an install is; an open session follows it.

verifySemanticVectors reads every block of every segment and checks it against its checksum, the check opening leaves out; it reads the whole set. A damaged segment is marked so that every later open refuses it, and the call throws artifactCorrupt: installing the release again repairs the set (download it again if it is gone). On a FAT or exFAT drive on Windows a repair under the same segment fails while a session holds the set open, since a mapped file cannot be replaced there, so close the session (disableSemantic) before installing it. An install that replaced bytes the check had read, while it read them, is not damage: nothing is condemned, and the call throws vectorsBusy, to verify again once the install has finished. A cancelled verification records nothing. semanticCoverage counts the open index's live lines the recipe embeds and those the set holds a vector for: one pass over the chunkKey column, or, on an index without it, a read of the whole store. Only live vectors of the generation the set serves count: a vector a later delta deleted covers nothing, as a search returns nothing from it. semanticCoveredBooks makes the same pass, at the same cost, and returns the filePath of every book with a live line the set holds a vector for (filePaths, sorted and distinct). Vectors are keyed by text, not by book, so a personal book or an attached library's copy of a covered book's text is covered too. Call it off the UI thread and cache the answer. setKey (opaque, compare for equality) changes exactly when the vectors the set serves change: any install of a base or a delta, by this engine or another tool, a compaction, a fallback to PREVIOUS. The answer also depends on the lexical index, and the engine returns no key for the index's state: recompute whenever the application changed the index (a book added, removed or reindexed), as well as when setKey changed. recoveredFromPrevious is true when CURRENT's generation did not open and the answer is for PREVIOUS's, as semanticVectorsInfo reports it; for instance, a generation another tool wrote was damaged. generation and vectorsLibraryVersion are reported too, but are no cache key: a fallback goes back to an older generation, and a directory emptied and installed again numbers its generations from the start.

openSemanticArtifact opens the vector set read-only and serves searchSemantic from it, hydrating every result from this index. It compares every field of the set's identity with this installation's, and nothing in its input is a value to type in:

field meaning
vectorsDir the vector set, as installed
modelPath the model queries are embedded with, an ONNX graph with tokenizer.json beside it: for the Meivin model, seforim-embed-round2-int8.onnx
modelIdentityJson the text of the model's identity file, the one the vectors were built with: the sidecar's config/models/meivin-round2-onnx/model.json for the Meivin model. It describes the model family, and the graph at modelPath must be one of its query_packages
onnxRuntimePath optional: the ONNX Runtime library the application ships, the first place the runtime is looked for and, once passed, the only one; not part of any identity, and compared on a repeat call, since a process keeps the first runtime it loads
scanThreads optional: how many threads a search scans the set with; null for the sidecar's default, half the cores and at most eight. 0 is invalidInput

The application's installation puts the data folder at <root>/otzaria/, with seforim.db and the model package in a folder of its own inside it (the graph, tokenizer.json, and the identity file model.json), the lexical index at <root>/index/, and the vector set at <root>/vectors/. ONNX Runtime ships with the application (onnxRuntimePath; on macOS inside the signed bundle) or sits in the model's folder beside the graph, as the build for that machine's operating system and architecture.

A set's vectors are keyed by the text each was embedded from, not by where it sits in an index, so nothing ties the set to one index: every search resolves its hits against the index that is open, by the key of each line's text, which an index of schema version 5 keeps in its chunkKey column. A commit after opening leaves the set serving. With the column a line that moved is found where it is now, in its book or in another (without it: see below); a text a book holds in several places is a line for each, so ungrouped every one is a result. A hit is at most 32 lines: first one for each book that holds its text — each book the set records it in, or, when it left them, each book the index holds it in now; under a filter, also each admitted book it arrived in — then those books' other lines of it, in that order, while the 32 last; lines past them are not semantic results of that hit, though lexical search still finds every one. A hit's lines score alike, so an ungrouped page shows them in that order: a line of each book before any book's second. A line whose text is gone, or whose embedded text changed with its neighbours, is not shown; and every line a search returns, grouped siblings included, is checked first by recomputing its key from the text the index holds. A semantic match that fails the check is dropped, or, when the lexical side found the line too, shown as a lexical result; fallbackReason counts them. Under a filter, a text that moved or was copied into an admitted book since the set was built is found there, and only there: its vector is weighed at its own score beside the scan of the admitted books, whose results are exactly what they would be had nothing moved; that needs the column too.

A line of an official book whose text is in the library database (TextStorage.libraryDb) is keyed, checked and shown from its library row, read as a result reads it: a row changed since indexing is keyed as it reads now, so a vector of its old text is not shown for it; while the line source cannot be read (unconfigured, suspended, busy) the hits cannot be checked, and the semantic half falls back with a reason. The query cache keys a search by the line source's generation and suspension too.

An index whose chunkKey column was written under another recipe — its metadata records another, or none — has no column this build uses. Keys are recomputed from the text, which is slower; every line returned is still held to its whole key, and a passage a book repeats is still a line for each, by its lineHash. A line under 20 characters is keyed with up to two neighbours on each side, so a short text a book holds in many places among other lines has its key only where the neighbours repeat too: once one line of the same lineHash is found not to hold the key, the others are recomputed only where their neighbours' lineHashes can spell the hit's text, and a hit stops after 16 lines that were recomputed and did not hold its key — which takes neighbours too short to have a lineHash (under 12 Hebrew letters), or one before the line that fills the 512-character cap alone — so such a hit may show fewer of a book's repeats than the column does. But a record's line is found only at the line the set recorded or within 16 lines of it in the same book: a line moved further within its book, or a text moved to another book, is not found, filtered or not; a filter scans the books it admits alone, so a text moved or copied into one of them is not found under it; and compaction keeps records as they are (re-anchoring needs the column). This matters only while the index and the vectors are of different library versions, or after the index changed on the device (a book added, reindexed or moved); an index and a set of the same library version agree line for line. A rebuild by this engine gives the column. On an opened set the calls that build vectors are refused as read-only. SemanticStatus reports the open set's vectorsLibraryVersion, vectorSegments and needsCompaction. INT8 vectors from x86 and ARM CPUs meet at about cosine 0.999, the same order as INT8 against fp32.

configureSemantic opens a development session. SemanticConfigInput states how the vectors are produced, and nothing in it is read from the model file. Every field but rootDir and onnxRuntimePath is part of the index's identity (the model file by its checksum, once it has loaded), so an index built under one value reports needsFullReindex under another.

field meaning Meivin ONNX
rootDir the sidecar's own directory
modelPath the model file, an ONNX graph with tokenizer.json beside it seforim-embed-round2-int8.onnx
modelId the model's name ArieLLL123/judaic-semantic-round2-onnx-zayit
embeddingDim the width of every vector 256
pooling how one vector is made from each text in-graph
maxTokens the token cap per text, as the model's backend counts it; at least 2 and at most 65,536 256
modelQuantization the precision of the weights; must not be empty int8 (fp32 for the full-precision graph)
embeddingTextVersion the text recipe; 2 prefixes [PASSAGE] to texts and [QUERY] to queries 2
onnxRuntimePath optional: the ONNX Runtime library to load, as on SemanticArtifactInput; not identity

An ONNX model needs the ONNX Runtime shared library at run time. The library is loaded, not linked, from the first of three places that is set, and only from it: onnxRuntimePath; else the file named by the OTZARIA_ONNX_RUNTIME environment variable; else the platform's default file name (onnxruntime.dll, libonnxruntime.so or libonnxruntime.dylib) beside the .onnx graph. A path or a variable that names nothing is refused, never skipped for the next place, and an empty onnxRuntimePath is invalidInput. A process holds one runtime: once one has loaded, a session that names another is refused as onnxRuntimeUnusable until the process restarts. The reference is Microsoft's official ONNX Runtime 1.28.0 release, and the oldest runtime API accepted is ONNX Runtime 1.17's; Microsoft's macOS build is arm64 only and needs macOS 14 (its LC_BUILD_VERSION minimum is 14.0), so on macOS 12 and 13, which this plugin supports, it is onnxRuntimeUnusable. Without one that loads, opening an artifact (or indexing, on the development path) throws an error that says "ONNX Runtime could not be loaded: …" and what each place held; semantic search reports itself unavailable, and lexical search is unaffected. That is not the "No embedding backend is available in this build" of a build without the backend: the fix is the library, not a rebuild. On macOS, a Hardened Runtime application loads only libraries signed by Apple or with its own Team ID, so ship the runtime inside the signed application bundle and pass its path as onnxRuntimePath. The ONNX backend is built for desktop targets (Windows, Linux and macOS) only.

Cancelling a search. searchSemantic takes a SemanticCancellationToken, an opaque object with a factory constructor SemanticCancellationToken(), a synchronous cancel() and a synchronous isCancelled. Create one per search and cancel it when a newer query supersedes the search. The search borrows the token rather than moving it, so cancel() returns at once on the isolate that started the search, while the search runs. The search looks at the token before its lexical phase; the sidecar throughout the semantic half (before and after it embeds the query, every 1,024 records of the vector scan, before and after fusion); and the search again before it hydrates the sidecar's results and before it paints the page, or, for a lexical fallback, once the fallback's page is ready. At the first look after the cancel it throws SemanticError with kind cancelled: not a failure, never answered with lexical results instead, and, when the sidecar stops it, leaving its caches as they were. A search past its last look returns its results. A token cannot be reset. It is required, since flutter_rust_bridge 2.13 cannot pass an optional borrowed object: a fresh token changes nothing.

Tuning the ranking. searchSemantic takes an optional ranking, a SemanticRankingOptions holding every parameter hybrid ranking runs on, in place of the ranking a search runs on without it. Its constructor's defaults are that ranking, so a caller names only what it changes, and SemanticRankingOptions.defaults() reads them from the engine; passing them is passing nothing. The defaults are unmeasured placeholders: calibrating them needs a labelled relevance set and a metric over the page, and this option exists so that can happen from the application without a release of the engine.

option default allowed what it does
fusionStrategy weighted weighted, rrf, adaptive by weight; by rank, 1 / (rrfK + rank) from each side; or by weight with BM25 min-max normalized when its scores run high
rrfK 60 at least 1, with rrf RRF's k; read by nothing else
alphaOverride null 0 to 1 one lexical weight for every query
alphaByQueryType quoted phrase 1, reference 0.85, one or two words 0.7, three or four 0.5, five or more 0.3, none 0.5 each 0 to 1 the lexical weight per kind of query; 1 - alpha is the semantic side's
bm25SaturationK 10 above 0 k in BM25's normalization score / (k + score)
semanticThreshold 0 0 to 1 below this normalized similarity a semantic candidate counts for nothing
agreementBonus 0.1 0 to 1 added to a line both sides found, fused by weight
phraseMatchBonus, rareTermBonus 0 0 to 1 scaled by the share of the query's quoted phrases, or rare words, a line contains
sectionCoverageBonus 0 0 to 1 added to a line whose section holds another result
duplicatePenalty 0 0 to 1 taken from each later line with the same text
metadataRankingEnabled false a semantic candidate's book and facets add to its score
candidateWindowMultiplier 2 1 to 10 semantic candidates fetched for each place in the window

A value outside its range, or not a number, is refused before the search runs, with or without a session: invalidInput, whose field is the option's name in the Rust struct (alpha_by_query_type.short, rrf_k). A build without semantic support ignores the options.

Failures and states. A failed semantic call throws SemanticError, an FrbException with three fields: kind, a SemanticErrorKind to branch on; message, the detailed text the call has always produced; and field, the field the failure is about when it is about one. Before, these calls threw AnyhowException with the same text. The status and the search envelope carry kinds too:

type field meaning
SemanticStatus state a SemanticState: notInBuild, notConfigured, ready; and for a development session empty (nothing indexed yet), needsReindex or failed
SemanticStatus errorKind the kind of lastError, non-null exactly when it is; a development session's sidecar reports its failures as text only, so they are internal here
SemanticSearchResponse fallbackKind why the semantic path did not serve the search, when it was asked to: notConfigured, featureNotInBuild or queryFailed; null when it served it, or was not asked

A kind is decided from the type of the failure, never from its message. Where one type covers two states, a fact decides: a set with neither CURRENT nor PREVIOUS makes unusable metadata a missing set rather than a damaged one, and a file where ONNX Runtime is looked for makes a runtime that did not load unusable rather than missing. The installation's own identity values are checked first, by the sidecar's own functions, so a value no build serves is invalidInput, and what opening refuses after that is the set's, the model's or the runtime's. More kinds will be added: a switch needs a default branch, which is best treated as internal.

kind thrown by, or reported in means what to do
notConfigured state, fallbackKind no session is open open the vector set
featureNotInBuild state, fallbackKind no semantic support in this build hide semantic search
artifactMissing openSemanticArtifact, verifySemanticVectors, semanticCoverage, semanticCoveredBooks, retirePreviousSemanticGeneration nothing at vectorsDir, or nothing ever installed there (no CURRENT or PREVIOUS) download and install the vectors
artifactCorrupt opening, installing, verifying, semanticVectorsInfo, semanticCoverage, semanticCoveredBooks, retirePreviousSemanticGeneration a set whose pointers, metadata or segments do not open or fail their checksums, an identity left unfilled (field), or a release whose segment is not the one its manifest describes. Retiring: the live generation does not open, and the one before it is kept install the release again, which repairs the set (download it again if it is gone); on a FAT or exFAT drive on Windows, close the session first
artifactIncompatible opening, installing sound vectors built for something else; field is the first field that disagreed: text.line_text_version, model.family_id, model.chunking_identity, store.store_format_version, store.vector_precision, metadata_version, or for a delta that does not follow the set delta.*. Installing, field segment_id: the release is a version the set has installed, published again with other bytes; the set is sound and keeps what it serves install the vectors built for this application and model; for segment_id, do not download it again, which is refused the same way: keep the set, or install the release into a new, empty vectorsDir and open that
artifactNotPublished installSemanticVectors the manifest is not the one whose digest was published download the official release
insufficientDiskSpace installing, compacting more free space is needed than the device has free space, and try again
modelMissing openSemanticArtifact, semanticIndexBooks no file at modelPath download the model
tokenizerMissing openSemanticArtifact, semanticIndexBooks an ONNX graph without tokenizer.json beside it install the whole package
modelInvalid openSemanticArtifact, semanticIndexBooks not a usable model, or its backend could not load it; or, with field model_path, a path that names no ONNX graph, such as a GGUF download the model again; for a path, point it at the package's .onnx graph
modelIdentityMismatch openSemanticArtifact, semanticIndexBooks the identity does not describe the model; field: query_packages, tokenizer_checksum, embedding_dim or pooling ship the matching identity file or model
onnxRuntimeMissing openSemanticArtifact, semanticIndexBooks no runtime where one is looked for: at onnxRuntimePath when it is passed provide ONNX Runtime there
onnxRuntimeUnusable openSemanticArtifact, semanticIndexBooks a runtime file that does not load, is too old, or is not the one already loaded replace it, or restart
backendNotInBuild openSemanticArtifact, semanticIndexBooks no ONNX backend in this build, as on Android and iOS a desktop build
sessionConflict configureSemantic, openSemanticArtifact another session, or other inputs, is open disableSemantic first
readOnlySession semanticIndexBooks, semanticIndexDiff, removeSemanticBooks, resetSemanticIndex, compactSemanticVectors, retirePreviousSemanticGeneration a build-side call on an opened vector set, or a call that changes the vector set on an index opened read-only nothing
reindexRequired semanticIndexBooks a development session holds vectors from another configuration resetSemanticIndex, index again
queryFailed fallbackKind the semantic half of one search failed show the lexical results
cancelled searchSemantic, and the calls that install, compact, verify, count or list covered books its SemanticCancellationToken was cancelled before it finished drop it: nothing failed, and nothing changed
invalidInput configureSemantic, openSemanticArtifact, installSemanticVectors, searchSemantic, compactSemanticVectors a value the call cannot take; field when known (model_quantization, max_tokens, model_identity_json, pooling, embedding_text_version, normalization_version, vectors_dir, segment_path, onnx_runtime_path, scan_threads, a ranking option such as alpha_by_query_type.short or rrf_k, or policy.<option>) fix the call
internal any an I/O error or a fault, including the lexical index failing under searchSemantic report message
vectorsBusy installSemanticVectors, compactSemanticVectors, verifySemanticVectors, retirePreviousSemanticGeneration another install or compaction of the set at vectorsDir is running, in this process or another (field vectors_dir); nothing was read or changed, and an open session keeps serving. Verifying: an install replaced bytes the check had read, and nothing was condemned try again once it has finished; never disableSemantic for it

Top-Level Functions

checkIndexCompatibility

IndexCompatibility checkIndexCompatibility({required String path})

Checks whether an existing index is compatible with the current search engine schema.

The engine writes an otzaria_index_meta.json sidecar file when it initializes a new, empty index. Without that sidecar, Tantivy's meta.json must have a readable full schema and an explicitly empty segment inventory before initialization is safe.

This engine reads and creates schema version 10 only, with LINE_TEXT_VERSION 4. Its fields match versions 7 through 9, but its text recipe uses contextual sup/sub boundaries through transparent formatting and zero-width controls, and canonical marks without CGJ. Every version through 9 is rebuild_required, including indexes built from PR #66 revisions 67f3193 (schema 8) and 4bb3589 (schema 9) with valid sidecars. Vector artifacts with text.line_text_version 1, 2 or 3 must also be rebuilt and republished. A Git-pinned build requires these compatibility checks even before a release is published.

The check compares the whole Tantivy schema as well as the declared version. Without the sidecar, existing segments have an unknown text recipe even if their fields match version 10, so they require rebuilding and are never automatically stamped as version 10. Call this check before SearchEngine.newInstance; the constructor retains its existing contract and does not enforce this preflight for callers that skip it.

Parameters:

  • path (String): File system path of the Tantivy index directory

Returns: IndexCompatibility

Common status values:

  • compatible: Otzaria metadata exists, declares a schema version this engine reads, and the index has that version's schema
  • legacy_compatible: Otzaria metadata is missing, but the full Tantivy schema is readable and the index has no segments
  • rebuild_required: The schema is unsupported or differs from its declared version, or existing segments have no sidecar proving their text recipe
  • engine_too_old: The index schema is newer than this engine supports
  • missing_index: The index directory does not exist
  • invalid_index_path: The given path is not a valid directory path

Library line source

Since schema 5 the index does not have to store the text of official books. A book indexed with textStorage: TextStorage.libraryDb keeps its lines in the inverted index only; when results are built, the engine reads each line back from the library database (seforim.db) and prepares it exactly as indexing did, so SearchResult.text is unchanged. Everything else (TextStorage.inIndex, the default) is stored as before.

// Once, before the engine touches SQLite (app builds share Dart's SQLite):
final entry = sqliteHostEntryAddress();          // BigInt; 0 = SQLite is bundled
// if (entry != BigInt.zero) register Pointer.fromAddress(entry.toInt()) with
// sqlite3_auto_extension, then open any connection. The entry stays registered (it only
// returns SQLITE_OK after the first open); the app may sqlite3_cancel_auto_extension it
// after that first open. It never cancels itself: doing so inside the callback would make
// that open skip the next registered extension.

Future<void> configureLineSource({required String dbPath}); // lazy; new path drops caches
Future<void> suspendLineSource();  // closes the file; waits for a running window
Future<void> resumeLineSource();   // undoes one suspend; the last drops all caches
Future<LineSourceStatus> lineSourceStatus(); // ..., generation, libraryFallbacks
Future<void> configureUserBooksLineSource({String? dbPath}); // personal books; null closes
  • addTextBook / addTextBookBytes take required TextStorage textStorage. Pass TextStorage.libraryDb only when the text is the \n-joined rows of an official book read from the library database; filePath must then be id:<bookId>. A document's segment is its row's 0-based position in the book's lineIndex order.
  • addTextBook / addTextBookBytes also take an optional Uint32List? storedLines: the line ordinals of a libraryDb book whose text is stored in the index anyway, as for inIndex. Pass the rows whose data: URIs (embedded images) indexing removed: read back from the database, each would cost its raw size on every result window, while its cleaned text is a few bytes. Those lines carry no lineCheck and are always ok; the rest of the book reads from the database. Ignored for inIndex; ordinals past the last line are ignored. Without it every line of a libraryDb book reads from the database, image rows included (decoded and stripped exactly as indexing did).
  • libraryDb needs the line source configured while indexing: the book's text is split into lines and their count is compared with the book's rows in the database. When they differ (a row containing \n, another database) or the source cannot be read (unconfigured, suspended, or busy past the 100 ms timeout), the book is indexed as inIndex instead — its text is stored and its results are always ok — a warning is logged and LineSourceStatus.libraryFallbacks grows by one. The return value is unchanged. Indexing does not honor a window's busy backoff (below).
  • DocumentInput.textStorage (optional) accepts only null or inIndex: addDocumentsBatch / upsertDocumentsBatch refuse a libraryDb document, since a ready-made document cannot be tied to its row. addPdfBook always stores its text.
  • addPdfBook indexes one document per usable page, joining its normalized layout lines with \n. Its return value is the number of indexed pages; 0 still permits an OCR fallback. segment and reference retain the page's index and reference. A result and the count both represent a page, even if it holds several occurrences. Proximity, any-order, paragraph and partial-word-match searches can use all of that page's lines. Ordered phrases retain the existing enumerator-skipping rule below. Stored text and regex input retain the original normalized markers and layout breaks; regex anchors and .* apply within each layout line. Snippets flatten layout breaks and show up to eight windows of matched words on a long page. The reader can call HighlightMatcher.findPdfWordMatches on the full plain-text page. It paints complete matching layout lines when present, or the matching words across the page when only their combination meets the word threshold.
  • Existing PDF documents indexed line by line remain readable. Reindex those PDFs to enable page-wide matching: their textHash is 0; new PDF books have a fingerprint of their raw page text and indexes instead. When adopting this engine, the app must mark PDF books with textHash == 0 as changed, use a nonzero fingerprint for its empty-PDF marker, and split OCR sidecars into actual pages (a sidecar without \f is otherwise one page). This needs no index-wide schema change. Test indexes made with an earlier revision of this unreleased page-indexing PR must reindex PDFs to add marker metadata.
  • addPdfBookBytes is addPdfBook over one UTF-8 buffer: for page i, ends[2i] ends its reference and ends[2i + 1] its text, each slice starting where the previous ended, and pageIndexes[i] is its index. The bridge encodes and decodes arguments on the calling thread. Pack off the UI isolate and pass Uint8List / Uint32List to avoid converting ordinary Dart lists. Transfer still takes O(bytes) synchronous work and can block the caller for large books; this API moves UTF-8 decoding and indexing to the worker, not the transfer itself. Valid UTF-8 slices borrow the buffer on the worker without per-page text copies. Invalid UTF-8, including a boundary splitting a code point, is replaced. ends must contain exactly two offsets per page, be nondecreasing, stay within the buffer, and end at its length; equal offsets allow empty references or texts. An empty page list requires an empty buffer. Invalid offsets return an error before any document is added.
  • Each library line carries lineCheck, a CRC-32 of its exact text (spacing, punctuation, nikud and markup included). Every library row of one result window is read in a single read transaction and must match its lineCheck, and its lineHash when that is not 0; see TextStatus below. A line is read first at lineIndex = segment; only when that row does not match is the book's row order mapped (and cached) to find it by position.
  • suspendLineSource must be called before the database file is renamed or replaced (Windows cannot replace an open file); while suspended, library results are TextStatus.unavailable. A write by another connection without a suspend is noticed (PRAGMA data_version) by the next window, which drops its cached lookups first.
  • While another connection holds a write lock on the database, a window waits at most 100 ms, its library results are unavailable, and the next second of windows does not touch the database at all.
  • The database is opened by its plain path, read-only, so UNC paths (\\server\share\...) work.
  • Personal books (filePath uid:<bookId>) can be indexed as libraryDb too: their rows are read from a second source, the user-books database set by configureUserBooksLineSource (the same line table, content as TEXT or a zstd frame of a zstd_dict dictionary). Everything above applies to it, with its own row-count check and LineSourceStatus.userBooksFallbacks, except suspension: the app keeps writing it (WAL) while the engine reads it, each window sees the last commit, and a row that no longer matches its line is stale. configureUserBooksLineSource(dbPath: null) closes the file (waiting for a running window) and leaves those results unavailable. LineSourceStatus.userBooksConfigured / userBooksOpen / userBooksGeneration report it.

Data Models

SearchResult

Result returned from SearchEngine.search()

Fields:

class SearchResult {
  String title;        // Document title
  String reference;    // Document reference/citation
  String text;         // Highlighted snippet or full text
  int id;              // Document ID (u64)
  int segment;         // Segment number (u64)
  bool isPdf;          // Whether document is PDF
  String filePath;     // Path to document file
  TextStatus textStatus; // ok | stale | unavailable
  bool continuesToNextLine; // the phrase runs on into the next line (id + 1)
}

continuesToNextLine marks a hit whose phrase starts at the end of this line and continues at the start of the next one (see Phrases across a line break). text is then the end of this line and the start of the next, joined at a <br>, with the words of both lines painted. It is set only when both lines read back as indexed; a hit whose next line is stale or unavailable is shown like any other hit of this line.

textStatus is always ok for text stored in the index. For TextStorage.libraryDb documents, ok means the displayed text is exactly the text that was indexed — not that it came from the same database row: identical lines can trade places, and a line still at its lineIndex after an earlier row was deleted without renumbering reads ok. stale — the database no longer holds the indexed line (changed in any way, moved or deleted); text is the database's current line at that position, HTML-escaped and unhighlighted (empty when the row is gone), and reindexing the book fixes it. unavailable — the line source is unconfigured, suspended, busy or unreadable; text is empty. SemanticSearchResult carries the same field.

Note: The text field contains a snippet with HTML highlighting when matches are found. Highlights are wrapped in <font color=red>...</font> tags by default (configurable via HighlightConfig). If no snippet is generated, it contains the full document text.


SearchPageResult

Result returned from the searchAndCount* family.

Fields:

class SearchPageResult {
  List<SearchResult> results;  // The requested page
  int totalCount;              // Total hits for the query
}

HighlightConfig

Optional snippet/highlight configuration accepted by search, searchAndCount, searchStream and searchFuzzyTerms.

Fields:

class HighlightConfig {
  String highlightPrefix;   // default: "<font color=red>"
  String highlightPostfix;  // default: "</font>"
  int maxChars;             // snippet length budget, default: 800
}

IndexCompatibility

Result returned from checkIndexCompatibility().

Fields:

class IndexCompatibility {
  bool compatible;             // Whether the current engine can use this index
  String status;               // Machine-readable status
  int? foundSchemaVersion;     // Version found in metadata, when known
  int requiredSchemaVersion;   // Version this engine creates and reads (8)
  String engineVersion;        // Rust engine package version
  String metadataPath;         // Expected otzaria_index_meta.json path
  String? reason;              // Human-readable detail for non-trivial states
}

Compatibility is controlled by the schema version, not by the package release number: compatible is the answer, and foundSchemaVersion below requiredSchemaVersion is not a reason to rebuild by itself. A patch release can keep the same schema version when no rebuild is required.


ResultsOrder

Enum specifying the sort order for search results.

Values:

enum ResultsOrder {
  Catalogue,   // Sort by the catalogue order of setBookOrder, then line
  Relevance,   // Sort by search relevance score (descending)
  Generation   // Sort by the generation order of setBookOrder, then line
}

Usage Examples

Full-Text Search Example

// Initialize search engine
final searchEngine = SearchEngine.new('/path/to/index');

// Add documents
await searchEngine.addDocument(
  ordinal: 0,
  title: 'Example Book',
  reference: 'Chapter 1',
  topics: 'category/subcategory',
  text: 'This is the full text content to be indexed',
  segment: BigInt.zero,
  isPdf: false,
  filePath: '/path/to/book.txt',
);

await searchEngine.commit();

// Search with regex
final results = await searchEngine.search(
  ['text', 'content'],  // Search for these terms
  ['category'],          // Filter by topic
  10,                    // Limit to 10 results
  2,                     // Allow 2 words between terms
  1000,                  // Max regex expansions
  ResultsOrder.Relevance
);

// Count matching documents
final count = await searchEngine.count(
  ['text'],
  ['category'],
  0,
  1000
);

Implementation Notes

Regex Patterns

The SearchEngine uses Rust regex syntax. Common patterns:

  • . - matches any character
  • .* - matches any sequence
  • \w+ - matches word characters
  • [אבגד] - character class (matches any of these Hebrew letters)
  • (pattern1|pattern2) - alternation

Topic Facets

Topics use hierarchical facet notation with forward slashes:

  • "category" - top level
  • "category/subcategory" - nested
  • "category/subcategory/item" - deep nesting

Documents match a facet query if their topic starts with any of the specified facets.

Dimension Facets (author / era / base)

Alongside the category path, a document can carry extra facet values supplied at indexing time (extraFacets on addTextBook/addTextBookBytes/addPdfBook/addPdfBookBytes/ addDocument/upsertDocument, or DocumentInput.extraFacets). Three English roots are reserved as filter dimensions (they cannot collide with Hebrew category names): /author/<name>, /era/<period>, /base (foundational books).

Filtering semantics (facets parameter, all search/count functions): the facet list is partitioned by root — each reserved dimension is its own group, and all other paths (the category tree) form one group. Within a group facets are OR'ed (prefix match, as before); across groups they are AND'ed. So ["/תנך", "/era/ראשונים"] = "in תנ"ך AND by a rishon", while ["/era/ראשונים", "/era/אחרונים"] = "either era". A call with only category facets behaves exactly as before.

Result Grouping (deduplication)

The exact/advanced/fuzzy search*, searchAndCount*, search*Stream and search*StreamWithCounts functions accept an optional grouping parameter (ResultGrouping?, default null = flat results):

  • sameSection — hits under the same heading in the same book (same sectionId; a PDF page is a section) collapse into one result with a count.
  • identicalText — lines whose Hebrew letters are identical (punctuation, spacing and quotes ignored; see lineHash) collapse across books. Lines shorter than 12 Hebrew letters never merge.

When grouping is active: limit/offset count groups; each returned SearchResult is the group's best representative (by the requested order) and carries mergedCount (total group size) plus merged (up to 10 sibling locations — title/reference/id/segment/isPdf/filePath, no snippet). SearchPageResult.groupCount / the first SearchStreamUpdate.groupCount report the total number of groups; totalCount and bookCounts remain raw hit counts.

Phrases across a line break

Every line of a text book is one document, yet an exact phrase (searchExact*, the string search* API) and an advanced phrase (searchAdvanced* with SearchScope.wordDistance and all words required, including distance/customSpacing, word options and acronym expansions) are also found when they continue from the end of one line onto the start of the next. The hit belongs to the first line and is counted once — also when that line holds the phrase on its own as well — so counts, per-book counts, facets and grouping agree with the results. A phrase crosses at most one line break. For a PDF, the document is a whole page: phrases can cross several layout lines inside it, and an ordered phrase can additionally continue across one adjacent page boundary.

  • What a line's edge is. Leading and trailing enumerators — (ג), [יא], {פ}, up to five letters, digits or quote marks in brackets — are not words of the text: the phrase continues from the last word before a trailing enumerator to the first word after a leading one. Paired readings such as (הוצא) [היצא] remain one content position at either edge, and either reading can match. The words of both lines count toward distance.
  • What stops a phrase. In text books: a heading line (<h…>), a line without words, or the end of a book. In PDFs: a missing or empty page, or the end of a book. An extraction-garbage layout line is dropped before page text is joined and does not interrupt the remaining page text.
  • Not across lines: vocalized searches (matchNikud/matchTaamim), fuzzy search, the sameParagraph/sameSection scopes and partial word-match modes (which already ignore order within a line), negative queries (a negative phrase excludes only lines that contain it), semantic search's lexical candidates, and documents added through addDocument/addDocumentsBatch. In PDFs these document-local modes use a whole page; a negative ordered phrase also skips internal layout-edge enumerators, but never excludes a page by crossing into the following page.
  • Ranking. Under ResultsOrder.relevance a cross-line hit scores half the BM25 score of one in-line occurrence on a line of average length, so it ranks below typical in-line hits. Catalogue and generation orders are unaffected.

The index records, per line, the positions of its first and last content words (lineFirst/lineLast, FAST) and their terms (lineEdge: <word, >word). A query matches each split of the phrase on its own — the left part anchored to the end of a line, the right part to the start of one — and joins them on consecutive document ids. Facet filters restrict the attributed first line before positional verification; the continuation is still read from its immediate neighbour. A rare continuation can drive neighbour lookups instead of scanning a broad selection of first lines.

PDF pages additionally record optional internal enumerator ranges after the ordinary first lineFirst anchor (or an explicit 0 when that edge is closed), as (start, end) position pairs, and a raw lineEdge flag. The existing first-value anchor contract and schema stay unchanged, including after segment merging. Phrases on flagged pages are verified from positional postings and these fast values; there is no stored-page read or scan of other pages' metadata. Only markers strictly between selected query words are omitted from their gap: markers themselves remain searchable, including in a phrase that explicitly selects one marker and skips another. A normal raw phrase match gets no additional score merely because its page has markers elsewhere.

Index Persistence

The search engine stores its index on disk at the specified path. The index persists between application runs and can be reused without rebuilding.

Thread Safety

SearchEngine is designed to be used from a single thread. If you need concurrent access, create separate instances or implement your own locking mechanism.

Memory Considerations

The search engine uses memory-mapped files (MmapDirectory) for efficient index access. The index writer is initialized with a 50MB buffer (50_000_000 bytes).


Language Implementation Guide

When implementing this API in other languages:

  1. Index Format: Use Tantivy-compatible index format or implement a translation layer
  2. Regex Engine: Ensure regex engine supports similar syntax to Rust's regex crate
  3. Field Types: Map types appropriately:
    • u64 → unsigned 64-bit integer
    • String → UTF-8 string
    • bool → boolean
  4. Snippet Highlighting: Implement HTML snippet generation with configurable highlight tags
  5. Facet Structure: Implement hierarchical facet matching with / delimiter
  6. Async/Sync: Constructor is synchronous, all other methods are asynchronous

Version Information

This documentation is based on the current implementation as of the latest commit. Check the repository for updates and changes to the API.