Referencia · §8.19

Text analysis, queries, indexes and BM25

text, §M14.21 T1–T6

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

An analyzer turns a text into terms — what a text index keeps and a text query looks for (§M14.21’s later steps). text::Analyzer has a name and analyze(text, out), which gives Token { term, position, start, end }: the term, its word’s position among the text’s words (a dropped stop word leaves a gap, so a phrase does not match across it) and its bytes in the text. The same text gives the same terms, always.

Analyzers are registered (principle 12) and kept for the process, as index methods are: text::add, a module’s through Registry::add_analyzer; text::named(name) finds one (42704 otherwise); nc_catalog.text_analyzers lists them. A module reaches them through ext::text (named, tokens, Analyzer, Token, register_builtins), and the bound expressions ScalarFunction::rewrite and found read and give as ext::Expr — nucleus_sql::ext is all of the SQL layer a module names (§M14.19). The built-ins (text::register_builtins, once a process):

Name Does
simple (the default, text::DEFAULT) words, lower case
porter Lucene’s EnglishAnalyzer, which Anserini’s BM25 baselines use: words, English possessives ('s, ’s) dropped, lower case, Lucene’s 33 stop words, the Porter stemmer of 1980 with its reference implementation’s departures (text/porter.rs)
danish, dutch, english, finnish, french, german, hungarian, italian, norwegian, portuguese, russian, spanish, swedish words, lower case, the language’s Snowball stop words, its Snowball stemmer
trigram every three characters of the whole text, lower case (SQLite FTS5’s trigram): words by their parts in any language

Words are UAX #29’s (text/words.rs): the standard’s rules WB1–WB999 over the word-break property and Extended_Pictographic (text/word_breaks.rs, generated from the Unicode 16 database by scripts/gen-word-breaks.py); a segment with a letter or a digit is a word — can't, 3.14, e.g, a_b whole, an ideograph alone, a katakana run together. ASCII is classified without a table search.

Stemmers: Porter’s, written here; the others are Snowball’s (text/snowball/): the runtime and the algorithms exactly as Snowball 3.0.1’s compiler generates them for Rust (only their use paths changed; #[rustfmt::skip] keeps them so), BSD licence in the module. Stop words: Snowball’s lists (text/stop_words.rs, generated by scripts/gen-stop-words.py), sorted by bytes for a binary search.

tokenize(text [, analyzer]) returns the terms an analyzer makes of a text, as an array (NULL for NULL): what an index on it would keep.

Tests: words.rs — every case of Unicode’s WordBreakTest.txt (crates/sql/tests/data/word_break_test.txt, comments removed); porter.rs — Snowball’s Porter vocabulary (the paper’s algorithm, the departures off) and the three departures; snowball/ — each language’s vocabulary; the vocabularies in the repository are every fortieth word, the whole of each checked where bench/text/data.py fetched them into target/text-data (Snowball’s data at the commit of 3.0.1); 56_text_analyzers.slt — tokenize with each kind of analyzer, the catalog view; tests/text.rs — every analyzer over any string (proptest): tokens at character boundaries, positions in order.

Text indexes (§M14.21 T4, text/index/): CREATE INDEX … USING text (col) WITH (analyzer = 'english') on one text column (another type 0A000; an analyzer not registered 42704; k1 and b, BM25’s parameters (T5: k1 ≥ 0, b from 0 to 1; Lucene’s 1.2 and 0.75 by default), else 22023 — as any other option), simple by default; the options keep analyzer, and k1 and b where given. The index decides what col @@ q means: its analyzer, given by the binder (IndexMethod::operand), on the rows as through the index; a filter’s col @@ q with q fixed for the scan is found by it (Access::Method, §8.17). A NULL is not indexed.

Storage (text/index/store.rs), model (C) as HNSW’s (§8.18) but exact in every snapshot. Keys under the index’s prefix: r the root (the segments, oldest first: object id, documents, deleted object, deleted count); o + id + part an object in parts of 1 MiB (ids are nonces, never reused: an object is written once); d + primary key + nonce a delta row (the text’s hash, its terms with positions, its length); x + primary key + text hash + nonce a tombstone (the old text’s length and distinct terms). A write puts one or both in its statement’s transaction (an update that leaves the text and key alone, none). A row is in the index as many times as its (key, hash) was inserted less the times it was deleted, wherever each is — segment, delta or tombstone — so a search counts versions: View::matching finds the segments’ documents not deleted and the delta’s rows that match, and drops those a tombstone of the same version cancels. View::stats(terms) — documents, total length, each term’s documents — adds the segments’ counts, takes off their deleted objects’ (each keeps its documents’ bits, count, total length and per-term counts), adds the delta’s inserts and takes off its tombstones: the snapshot’s rows’ numbers, which BM25 (T5) reads.

Upkeep (text/index/mod.rs): a write notes its index; after a statement, once SEAL (1,024) rows wait, the session seals — in a transaction of its own (hnsw::retrying), one index at a time (Pending::busy) — the delta into a segment: a tombstone of a row in the delta drops it, one of a row in a segment marks it in a new deleted object for that segment (Segment::find_doc by key and hash); a segment all deleted goes; the delta’s keys are deleted and their range vacuumed. Then merges: MERGE (8) segments of a tier — live documents in powers of 8 — written as one, the deleted documents left out (Tantivy’s logarithmic policy). upkeep_now (tests, VACUUM), merge_all, shape and stats are public for tests. CREATE INDEX reads the rows’ texts, then analyzes them and makes segments on the statement’s workers (parallel_workers) — a batch each, the rows over the workers, 512 to 100,000 a segment (Lucene’s and Tantivy’s indexing threads, a segment each; build_segments, the sparse and JSON indexes’ builds too) — and runs the merges due a round at a time, a round’s groups at once and each group’s terms in runs on its share of the workers (segment::merge: cut at terms of the part with the most, joined in order; the same bytes as one run). Where the batches’ segments hold 3 GB or less together they are merged into one at once, in memory, before any is written (Store::append_merged, on the workers; Lucene’s forceMerge(1) for an index done with) — a search looks each term up once a segment, and one merge reads each document once — else the merges due run.

Segments (text/index/segment.rs): documents (primary key, text hash, length), terms sorted, each with its document count and its postings in blocks of 128 — the documents’ deltas and the frequencies less one, each bit-packed at the block’s width (Lucene’s and Tantivy’s layout, the bits a block needs, no SIMD yet) — and its positions apart (varint deltas), read only for phrases. Version 2: a term in more than one block has a skip list — per block its last document, its bytes and its impacts, the (frequency, length) pairs of its documents no other there beats (Lucene’s competitive impacts, a Pareto frontier) — so a search reaches a block without decoding those before and bounds its scores without decoding it (Segment::blocks, block); version 1 is read, its skip lists made as it is decoded. A segment is decoded once into memory and shared by every snapshot (object_cache, the HNSW index’s cache moved out of it: Kind::TextSegment, TextDeleted). A search decodes each leaf’s postings (a prefix’s terms by a range of the dictionary, a fuzzy term’s by a pass over it), evaluates the query’s tree over sorted document lists (intersections, unions — of many lists through a bitmap of the segment’s documents —, differences; phrases checked on their candidates’ positions) and the delta’s rows by their stored terms.

Tests: segment.rs — bit packing at every width, a segment of several blocks round-tripped, a merge dropping deleted documents, every block of a skip list reached and bounded by its impacts (version 1’s made alike), a merge in runs the same bytes as one; tests/text_index.rs — through a build, a delta of updates, deletes, inserts, a rollback and a row changed back and forth, seals, twelve rounds of writes and merges, a merge of everything, the table emptied: at every step each of eleven queries through the index against the same on the rows, and the integrity check (the rows’ versions, the documents, lengths and every term’s document count); a snapshot keeps its statistics through writes and seals; the index decides the analyzer; a row deleted in a segment stays deleted; tests/text_index_crash.rs — a crash at any I/O point of a workload of writes, seals and merges (dropped and torn writes), then the rows of some step, the index exact and its answers the rows’, and writes and an upkeep after; and a transaction’s snapshot keeping its answers and statistics while other sessions write, seal and merge; 58_text_index.slt — the syntax, the catalog, EXPLAIN, the analyzer with and without the index, writes and a rollback.

BM25 (§M14.21 T5, text/score.rs): score(col @@ q), on a column with a text index, is how well each row’s text matches q — Lucene’s BM25Similarity over the index’s statistics as the statement’s snapshot sees them: a term’s idf · tf / (tf + k1 · (1 − b + b · dl / avgdl)), idf = ln(1 + (N − n + ½) / (n + ½)), with the text’s exact length in terms (Lucene keeps a byte); a phrase’s, of its frequency with its terms’ IDFs summed; a prefix’s or a fuzzy term’s 1 where it matches (Lucene’s constant score); a boolean query’s, the sum of its required and matching optional parts’ — a word twice in a query counts twice; 0 where the query does not match, a NULL text too. Without a text index score is refused when bound (0A000), as is a query that varies by row.

Over rows no index holds — a sealed memory store’s (§8.40), one user’s — BM25 is asked for by its parts: bm25_stats(text, q [, analyzer]), an aggregate, gives the statistics of the rows it is fed (float8[]: documents, their total length in terms, each of the query’s leaves’ documents — a prefix’s and a fuzzy term’s 0), and bm25(text, q, stats [, analyzer]) scores a text by them with Lucene’s k1 1.2 and b 0.75 (0 where it does not match; in rrf/convex it ranks the rows text @@ q holds for alone, as score does). The query must be the same for every row (0A000); statistics of another query are refused (22023).

The text index binds it (IndexMethod::function, §8.17; text::score::bind) as text_score(col, q, analyzer, k1, b, (SELECT text_stats(table, index, q))): the statistics — documents, their total length, each exact term’s documents (View::stats) — in an uncorrelated subquery, read once a statement; text_score scores a row’s text by them (Scorer, the query analyzed with the index’s analyzer). ORDER BY score(col @@ q) DESC LIMIT k over a scan the index finds the rows of (WHERE col @@ q, with other conditions, a join’s key filters or row-level security or not) is ranked by the index (IndexMethod::rank, §8.17): View::ranked(q, sc, n) scores from the postings — their frequencies, positions for phrases, the segment’s lengths — through the same Scorer, so the numbers are a row’s, the n best matches and every one tied with the n-th (all of them where Ranked::complete), and the rows are read greatest first in slices (Ranked::next: a selection over the rest, then a sort of the slice) — k over the share the optimizer expects to pass the other conditions first, then as many as the share passing so far needs, at least as many again — until k passed and every row tied with the k-th passing one has been read (a lookup each, in that order: it stops at the k-th exactly — a merge with the table’s scan, as a served condition’s rows are read, measured slower here; PLAN.md §M14.21 T5b); the sort and the limit above order them — by the scores the ranking gave with the rows (RankAsk::values, §8.17): score() does not analyze a returned row’s text again (PLAN.md §M14.21 T5c); text_score scores the rows only where the index cannot rank them (a query of score not the condition’s). n is k where no other condition is, else four times the rows the expected share takes; every match is scored where n is a 64th of the matches or more (about: no more than the documents or the leaves’ documents together), and where the first n run out before k pass, a second pass takes four times the rows the share seen so far needs (by the same rule), a third every match — never more than two passes and a full scoring.

A bag of words (one term, or optional terms only) is scored by block-max MaxScore (Turtle and Flood’s; Lucene’s MaxScoreBulkScorer, View::live_matches → max_score): the threshold is the n-th best score of the versions found so far (Top); documents in windows of 4,096 (the first a leaf the threshold leaves essential over the segment holds); in each, the leaves sorted by their bounds there — their blocks’ impacts’ best score, by the snapshot’s statistics, a unit more — and those whose bounds together stay below the threshold non-essential: a document only they hold cannot reach it, a window none is essential in is skipped. The essential leaves’ postings are summed term at a time into the window’s buffer; the documents found that may still reach the threshold are the candidates; each non-essential leaf, best bound first, is matched against them — its postings read through where they hold four times the candidates or fewer, else each candidate looked up (Cursor::advance: blocks skipped by their last documents, undecoded) — and candidates that can no longer reach it dropped. A term in one block is decoded into its cursor once, its bound the score of its greatest frequency in its shortest text; with no threshold (every match wanted) the leaves’ postings are summed term at a time over the segment, no windows (every_match). Scores are summed in fixed point, units of 2⁻³² (score::fixed), in the index and on rows alike: integer sums, the same whatever order the terms are added in, so MaxScore adds them in its own and the numbers are still a row’s (as PISA’s and JASS’s quantized scores, far finer: 2.3 × 10⁻¹⁰). A block’s bound is its best impact’s score rounded as a part is, plus a unit, so only documents that cannot reach the threshold are skipped: the ties of the n-th stay. Any other query is scored document at a time over cursors into each leaf’s postings. A version is counted only where a tombstone in the delta names it: a segment’s document not marked deleted is otherwise live and the only copy of its row (View::live_matches) — the copies of a named row are of one text and score alike, so a threshold another reaches leaves none of them out; only versions not named raise it.

Tests: score.rs — the formula against a computation by hand, sums over the tree, phrases, prefixes; store.rs — MaxScore’s matches over segments of many windows (windows skipped, documents skipped to, deleted documents) against every document scored on its text, at n from 1 to all: the best, their ties, the same scores; 59_text_score.slt — scores against a computation outside, the refusals, EXPLAIN, the first rows with an offset, ties; tests/text_index.rs — at every step of its writes, seals and merges, eleven queries’ first seven rows by score through the index against the same scored on the rows (scores to the last bit, ties broken alike); pruned_as_scored_in_full — a Zipf vocabulary, texts of very different lengths, an index built on four workers, deletes in segments and the delta: seven queries at five k with three filters, through the index and on the rows, alike. bench/text/beir.py checks the rankings against Anserini’s and ParadeDB’s on BEIR (docs/benchmarks.md).

On every kind of table (§M14.21 T8c): a text or sparse index is a table’s whatever its storage — it is told each row written and builds over the rows the storage gives (§8.15), row, column and row,column alike — and CREATE INDEX on a partitioned table makes one on each partition (§8.16). A partitioned table’s query is its partitions’ scans, each served by its own index: @@‘s rows, and the first k by BM25 or by <#> from each, the sort above keeping the first k of them — their scores read from the indexes (with values) where every partition’s gives them, else computed again on the rows kept —; rrf and convex likewise (§8.20). BM25’s statistics are the partitioned table’s — documents, their length and each term’s documents summed over its partitions’ indexes (text::index::stats: each partition’s index of the same definition, looked for past the table’s place where the partition has indexes of its own) —, so a row scores as in one table, whichever partition holds it; under row-level security, those of the partitions the policies let the statement read (text_stats‘s fourth argument; §9, “Retrieval under it”). Tests: tests/text_tables.rs — a row, a column, a row,column table and one partitioned into partitions of each storage, the same rows written to each: built over a load, then inserts, updates, deletes, rows moved between partitions, and sealed; at each step eight queries’ rows, their first seven by score with three filters, highlights and snippets, the first by <#> and rrf and convex of both alike to the row table’s (scores to the bit), served by the indexes (the scores read from them), and the integrity check. On BEIR (bench/text/beir.py --layout, docs/benchmarks.md) a column table ranks as fast as a row one, one partitioned four ways in about twice the time, the same nDCG@10.

Text queries (§M14.21 T2, text/query.rs): text @@ query is true when the text matches the query. The syntax is Lucene’s, the subset of it one column needs, so what people and models already write works:

Query Matches
word the word, analyzed as the text is; a word the analyzer makes several terms of (e-mail, P/E, any word under trigram) is a phrase of them; a stop word is dropped
"some words" a phrase: the terms at consecutive positions (a dropped stop word keeps its place)
"some words"~N the phrase within N moves (Lucene’s slop: a word between is one, a transposition two; N up to 1,000)
word* any term starting so — lower-cased, not stemmed (Lucene’s normalization)
word~, word~1 any term within 2 (1) edits — insertion, deletion, substitution, transposition of neighbours; lower-cased, not stemmed
a b either (Lucene’s, Tantivy’s, Elasticsearch’s default: ranked search wants any of them)
+a b a required, b then only ranks
-a, NOT a without a; a query of exclusions only matches the texts without them
a AND b, a OR b, ( … ) NOT binds tightest, then AND, then OR, then words side by side

AND, OR, NOT are operators in upper case only; + and - only before a word (C++, a - b are words). Other punctuation breaks words as the analyzer does, so a question typed or generated as plain text is a query. A malformed query — an open quote or parenthesis, a AND, ~3 — is a 42601 error with the character it was found at.

The query is parsed once into its distinct leaves (exact, prefix and fuzzy terms) and a tree of Leaf, Phrase and Lucene’s Bool { must, should, not } over them; a text is analyzed, each term’s positions noted for the leaves it matches, and the tree evaluated. A phrase’s occurrences come from one function (query::phrase) wherever positions are read — a row’s text, a segment’s postings, BM25, a highlight: exactly, each position of its first term the others follow at their offsets (binary search); within a slop, Lucene’s SloppyPhraseMatcher — each term’s position less its offset, the least moved on (through the positions that keep it least, so the tightest occurrence from there counts), an occurrence where the greatest less the least is at most the slop, weighing 1 / (1 + that) in BM25’s frequency (§M14.21 T6; a term twice in one phrase may share a position, as Lucene’s would without its repeats’ rule). The analyzer is a third, optional argument of the operator’s function, which the binder gives from the column’s text index — one meaning with or without an index; without one it is simple. The batch kernel parses a constant query once a vector; a row at a time, a per-thread cache keeps the last query parsed.

Highlights and snippets (§M14.21 T6, text/highlight.rs): highlight(col @@ q [, start, stop]) — the text with what the query found marked, <b> and </b> by default — and snippet(col @@ q [, start, stop, ellipsis, words]) — its best window of words terms (PostgreSQL’s MaxWords, 35; 1 to 1,000), marked, ... where the text goes on. Functions of the condition, as score is: the binder binds them (ScalarFunction::of_condition / bind_condition, §8.12) as text_highlight(text, q, analyzer, …) and text_snippet(…) of the @@ call’s operands — its analyzer the column’s text index’s, simple without one — so a text is analyzed as @@ analyzes it; of anything but @@, refused (0A000). Marked: each word an exact, prefix or fuzzy term finds, each occurrence of a phrase (within its slop) from its first word to its last as one mark (SQLite FTS5’s highlight), nothing only an exclusion names; overlapping marks are one; the text between is kept as it is, not escaped (ts_headline neither). The snippet’s window holds the most distinct leaves, then the most marked terms, the earliest of equals (FTS5’s order), and is moved to put its marks in the middle where they leave room; a text with nothing found gives its first words terms, an empty one nothing.

Tests: query.rs — the operators, phrases across stop words, phrases within a slop and their weights, prefixes and fuzzy terms under a stemmer, plain text as a query, syntax errors, the edit distance, and any string as a query (proptest: an error or an answer, never a panic); highlight.rs — marks, phrases as one, slops, prefixes, stems, overlaps, snippets’ windows; 57_text_queries.slt — @@ on rows, NULLs, a query that varies row by row, the errors, in every executor mode; 60_text_highlight.slt — highlights and snippets with and without an index, slops ranked by the index against a score computed by hand; tests/text_index.rs — two phrases within a slop among its queries, the index’s rows and scores the rows’ at every step.