Repository navigation
planner: count FULLTEXT index postings when planning - #73114
terry1purcell wants to merge 16 commits into
Conversation
|
Skipping CI for Draft Pull Request. |
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:
Approvers can indicate their approval by writing |
45cc5ee to
27083d1
Compare
…ysis Add the parsing and analysis a FULLTEXT search needs, with no SQL behaviour change yet: - pkg/expression/matchagainst parses IN BOOLEAN MODE search strings for the STANDARD and NGRAM parsers, following MySQL's operator grammar. - pkg/expression/fulltext tokenizes documents the way InnoDB's built-in and ngram parsers do (token size bounds, the default stopword list, ngram positions), and compiles a boolean search into a query that can match a document. - innodb_ft_min_token_size, innodb_ft_max_token_size and ngram_token_size become real global variables, bounded as in MySQL, so the analyzer reads them; they were read-only placeholders. - model.FullTextParserTypeNgramV1 names the NGRAM parser. This is the first part of splitting pingcap#71531 (FULLTEXT index in TiKV) into staged PRs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…oken-size bounds - NGRAM positions: a word too short to yield a gram left no gap when an earlier word had more grams than words, so the distance between the grams around it depended on the preceding text. A phrase such as "gh x ij" then missed a document containing it, and "gh ij" matched it. Positions now come from a running counter: one per gram start, and one per word too short for a gram. - STANDARD parser: a quote left open now runs to the end of the search string, and a newline no longer ends it, as in the NGRAM parser. It was an error, so a stray quote failed the statement under one parser and not the other. - innodb_ft_min_token_size and innodb_ft_max_token_size are validated against each other. Their ranges overlap, and a minimum above the maximum made the STANDARD analyzer drop every token, so every search silently matched nothing. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
… operators
- A required term that is a stopword or outside the token-size bounds
made the whole search match nothing, while the same term without '+'
was ignored. It is now dropped, as MySQL transforms '+word +stopword'
into '+word'; a search left with no positive term still matches
nothing.
- '~', '<' and '>' were errors. In MySQL they only change a word's
contribution to the relevance, and MATCH is evaluated here as a filter
without a score, so the word after them is optional. '(' ')' and '@'
stay unsupported.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
b125834 to
70f2de5
Compare
…equired term UsesPrefixPostings reported a prefix anywhere in the query, including an optional one in a group with a required child, whose postings are never read. It now follows the lists PostingReads names. Also document the two exported NGRAM parsing errors separately. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
3942ab0 to
04464cc
Compare
…GRAM delimiter A word of Hindi, Thai or vocalized Arabic holds a combining mark, a vowel sign or a virama, between most of its letters. The tokenizer took only letters, numbers and '_' as word characters, so it split such a word at every mark, into single letters that the STANDARD analyzer then dropped as too short. Marks are now word characters, in the analyzer and in the NGRAM search-string scanner, which must agree with it. The NGRAM scanner follows MySQL's fts_get_word, which an index WITH PARSER ngram is searched through: a prefix operator counts only after a space, the last of several wins, and a stray one is skipped. '@' is no operator there, only a delimiter, so it no longer fails the statement and an address can be searched for. Also remove code no search string can reach: - the NGRAM parser's parenthesized groups, which its scanner rejects first, and with them ErrUnmatchedLeftParen and ErrUnmatchedRightParen; - BooleanGroup as a clause expression, BooleanTerm.Ignored and BooleanPhrase.Distance, which no parser sets; - the STANDARD scanner's NUM token, which only followed the '@' the parser rejects, and the commented-out parseGroupClause. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
0bff5d4 to
0a78e77
Compare
755e775 to
8704e1c
Compare
…ted token sizes - In an NGRAM boolean search, '>', '<' and '~' after a space are consumed as operators, as MySQL's scanner does, so '+>apple' stays required and '->apple' excluded instead of both becoming optional. - The analyzer refuses innodb_ft_min_token_size above innodb_ft_max_token_size when it reads them. Each SET checks the other variable, but concurrent updates, or updates between the two reads, can still give such a pair, and the STANDARD analyzer would then drop every token and match nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
56e5eac to
70f5e7f
Compare
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
On the classic kernel, store a FULLTEXT index in TiKV as a positional inverted index: one KV entry per distinct term per row, whose value holds the term's positions in the document. Creating one requires the new undocumented variable tidb_enable_tikv_fulltext_index (default OFF); without it CREATE TABLE, CREATE INDEX and ALTER TABLE ADD fail with the same error as before. The switch is removed once queries can read the index. - Metadata: IndexInfo.TiKVFullText snapshots the parser and analyzer settings (token sizes, stopwords, ngram size) when the index is created, with a format version. The statement's session captures them into the ADD INDEX job, so the owner builds with the same settings. WITH PARSER NGRAM selects the ngram parser. - Columns: the last index column is tokenized; any columns before it are ordinary key columns encoded ahead of the term, so one tenant's entries form a contiguous range. Prefix lengths, DESC, GLOBAL, partial conditions, expression key parts, non-string or binary columns and local temporary tables are refused. - Write path: the index tokenizes the row and writes one entry per term; a NULL, empty or stopword-only document writes none. The mutation checker checks each entry's term and key columns against the row. An index whose version this binary does not know fails its writes rather than its schema load. - ADMIN CHECK TABLE / INDEX checks a FULLTEXT index from the record side: every row's expected entries exist, and every entry belongs to a row. ADMIN CLEANUP INDEX refuses it. - DDL guards: creating the index needs DDL job version 2 and every TiDB node to support it. SHOW CREATE TABLE prints it with its parser, BR log restore can rebuild it, and ANALYZE, auto-analyze, TTL and access-path selection skip it. This is part 3 of splitting pingcap#71531 (FULLTEXT index in TiKV) into staged PRs; it depends only on part 1. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A relevance score such as BM25 needs, from each posting it reads, the term's frequency in the document and the document's length. The frequency is the position count; store the length, in tokens, ahead of it, so a score can later be computed from the postings alone without reading or analyzing the document. A row's entries are all rewritten when its document changes, so the length cannot go stale. The new layout takes value kind 0x02; the pre-release kind 0x01, without the length, is refused rather than misread. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add tidb_enable_local_match_against (default OFF). When it is on, a MATCH ... AGAINST ... IN BOOLEAN MODE in a filter position (WHERE, ON, HAVING, under NOT or parentheses) is evaluated in TiDB with the analyzer and boolean query from pkg/expression/fulltext, instead of erroring without a columnar index or being approximated by the ILIKE fallback. - The analyzer settings are resolved from the session at plan time and frozen into the builtin, so every row is tokenized the same way; plans that use them skip the plan cache. The switch is part of the plan cache key, so a plan built with it off is not reused with it on. - A constant search string is compiled at plan time, so syntax errors surface even when no row reaches the filter, and a query that matches nothing is known to the estimator. Any other search string is compiled per value at execution. - The search modifier and the place of evaluation are part of the builtin's hash codes and equality, so a BOOLEAN MODE search and a natural-language one over the same column and string stay two predicates. - Natural-language mode, query expansion and scoring positions (SELECT list, ORDER BY, comparisons) keep the existing behaviour: a 0/1 result is never substituted for a relevance score. - The estimator uses one analyzed term as its ILIKE proxy, and the cost model charges a locally evaluated MATCH by document size. - Column substitution keeps the planner state on the builtin by cloning it, and a local MATCH is never pushed to TiFlash. This is part 2 of splitting pingcap#71531 (FULLTEXT index in TiKV) into staged PRs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Building a subquery set the plan builder's current clause for its own clauses and left it there, so the rest of the enclosing expression, and the next select-list item, ran as if in the subquery's last clause. A local MATCH after such a subquery was then misclassified: in the select list it was evaluated as a 0/1 filter instead of refused as a score, and in WHERE it was refused although it is a filter. buildSubquery now restores the clause, as it already restores the window specs and the subquery context. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add the engine that answers a compiled MATCH ... AGAINST boolean query from an inverted index instead of one document at a time. The index is abstracted as a PostingSource that opens the posting list of a term or a prefix; nothing here reads TiKV yet. - Query.OpenPostings mirrors the query tree with streams that each yield handles in ascending order without duplicates: a term reads its list, AND intersects by leapfrog seek when the source supports seeking, OR unions by merge, a phrase aligns positions, and prohibited children are subtracted. A term read only for its handles skips its positions. - The result is exactly the rows the query matches, given an index built with the analyzer the query was compiled with. - Query.EstimatePostingCost estimates the postings read and rows yielded under a cost model the planner supplies, accounting for seeks; and Query.RowsFromPostings reports whether the postings alone decide the match. - Memory for buffered postings is reported to the source when it implements PostingMemoryConsumer. The tests compare every stream against evaluating the query document by document, including randomized queries. This is part 4 of splitting pingcap#71531 (FULLTEXT index in TiKV) into staged PRs; it depends only on part 1. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…TiKV Queries now read the FULLTEXT index that part 3 builds in TiKV, so the switch that gated creating one, tidb_enable_tikv_fulltext_index, is removed: on the classic kernel CREATE TABLE, CREATE INDEX and ALTER TABLE ADD build the index without it. - Rewriter: a MATCH over a single column that a public TiKV FULLTEXT index tokenizes is evaluated locally even without tidb_enable_local_match_against, and compiles with the analyzer settings recorded in the index, so the query searches for the terms the index stores. The column is traced to the data source that produces it, not looked up by name. - Planner: such a MATCH stays with the data source, which adds an IndexMerge path whose single partial path is a FullTextIndexScan. Key columns ahead of the term must each be pinned by an equality; handle ranges narrow the postings read. The path's cost counts the postings read and the seeks, estimated from column statistics through each term's ILIKE form, and the path is kept to compete on cost rather than pruned by heuristics. Any other path evaluates the MATCH as a root filter. The path cannot keep an order. - When a Limit or TopN under tidb_opt_limit_push_down_threshold prefers pushed-down plans, a coprocessor task still shuts out the root tasks, except an IndexMerge, which runs only as a root task, while every coprocessor task leaves conditions for the root, as every one does under such a MATCH, and so takes no Limit or TopN either. An OR IndexMerge on ordinary indexes is no longer shut out of such a query. - Executor: the FullTextIndexScan reads posting lists from TiKV with the posting-list engine of part 4, seeking where AND allows, and feeds the handles to the table-side probe. It honours KILL, tracks memory and reports runtime statistics. Inside a transaction, UnionScan finds the transaction's changed rows from the table records. This is part 5 of splitting pingcap#71531 (FULLTEXT index in TiKV) into staged PRs; it depends on parts 2, 3 and 4. Part 6 adds the planning-time count of each term's postings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
70f5e7f to
c0215a6
Compare
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A FULLTEXT index has no statistics of its own, and its text column often has none either, since ANALYZE skips long text by default. The postings of an exact term are one contiguous key range, so the planner now counts them in TiKV while planning, instead of relying only on the column statistics as part 5 does. - Each term's first count reads at most 64 entries in one physical table, within one kv_scan batch. A term with fewer postings is counted exactly; a common one keeps its statistics estimate, but never below the count read. When every term of a search is common, the longest is counted further, up to 1024 entries. One statement probes at most 32 terms, each term once, and counts at most 4 of them further. - Nothing is counted, and no FULLTEXT path offered unless a hint names the index, when another access path already reads at most 64 rows: no posting scan can beat it. - An index with key columns pinned by the conditions is preferred to one without on the same column: it reads a part of the same postings, so the index without key columns is neither probed nor offered for that MATCH unless a hint names it. - A partitioned table probes at most 4 partitions and scales the counts; the scaled count is the estimate. Partitions planned one by one share a term's probe: the first 4 count it and the others take their mean. - The probe reads its own snapshot at the statement's read timestamp, keys only, and stops when the statement is killed. A failed read falls back to the statistics and never fails planning. - Rows the transaction has written, and those of a temporary table, are not in TiKV to be counted, so such a table is not probed. - The counts feed the cost of the FULLTEXT index path, so a rare term uses the index and a common one scans. - A MATCH that a FULLTEXT index can answer gets its selectivity from the counts, which every path and the rows estimate of the data source use for the rest of the statement. For an index with key columns, the term is counted under the point the other conditions pin them to. - A statement kept from TiKV, by tidb_isolation_read_engines or a TiFlash hint, does not probe. - The selectivities of string-match filters are cached per statement: planning evaluates the same filter against the column's TopN and histogram for every access path and task, which for a long text column was the bulk of planning time. This is part 6 of splitting pingcap#71531 (FULLTEXT index in TiKV) into staged PRs; it depends on part 5. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
IndexMerge sized the rows its table side sends back with the per-column type width whenever a column has no statistics, while IndexLookUp uses the pseudo column size. On a wide table whose TEXT columns lack statistics the two readers then disagree by more than an order of magnitude on the same rows, and an ordered IndexLookUp under a LIMIT that reads many more rows looks cheaper than a FULLTEXT IndexMerge that reads few. Use the IndexLookUp row size for the IndexMerge table side. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
c0215a6 to
4c258d9
Compare
What problem does this PR solve?
Issue Number: ref #70491
Problem Summary:
Depends on #73110 (part 5, which sits on parts 1–4). Until they merge, this PR also shows their commits; review only the top two commits,
planner: count FULLTEXT index postings when planningandplanner: size IndexMerge table-side rows as IndexLookUp does.This is part 6 of 6 of splitting #71531 (FULLTEXT index in TiKV) into staged PRs:
MATCH ... AGAINSTevaluation without an index (expression, planner: evaluate MATCH ... AGAINST IN BOOLEAN MODE in TiDB #73086)ADMIN CHECK, with creation behind a switch (ddl, table, executor: build a FULLTEXT index in TiKV behind a switch #73088)A FULLTEXT index has no statistics of its own, and its text column often has none either, because ANALYZE skips long text by default. Part 5 estimates how many rows contain a term from the column's statistics alone, which is coarse.
What changed and how does it work?
The postings of an exact term are one contiguous key range, so the planner now counts them in TiKV while planning.
Limits:
Partitions:
Read: the probe reads its own snapshot at the statement's read timestamp, keys only, and stops when the statement is killed. Its reads are charged to the resource group but not added to the statement's own RU details.
Fallback: a failed read falls back to the statistics and never fails planning.
Not probed: a table the transaction has written to, and a temporary table. Their rows are not in TiKV to be counted, so the statistics estimate stands.
Skipped: no term is counted when another access path already reads at most 64 rows. A keyed FULLTEXT index serves a
MATCHbefore a plain index on the same column, so the plain one is neither probed nor costed, unless a hint names it.Uses: the counts feed the cost of the FULLTEXT index path, so a rare term uses the index and a common one scans. A
MATCHthat a FULLTEXT index can answer gets its selectivity from the counts; every path, and the data source's row estimate, use it for the rest of the statement.Engine isolation: a statement kept from TiKV, by
tidb_isolation_read_enginesor a TiFlash hint, does not probe.Selectivity cache: the selectivities of string-match filters are cached per statement. Planning evaluates the same filter against the column's TopN and histogram for every access path and task, which for a long text column was the bulk of planning time.
Row size on wide tables: IndexMerge now sizes the rows its table side sends back as IndexLookUp does. It used the declared width of every column without statistics, while IndexLookUp uses the pseudo column size. On a wide table whose TEXT columns lack statistics the two disagreed by more than 30x for the same rows, so an ordered IndexLookUp under a
LIMITthat reads many rows and filters them with theMATCHlooked cheaper than a FULLTEXT IndexMerge that reads few. On a 370-column test table this ordered plan prefetched over 1 GB and exceededtidb_mem_quota_query; the FULLTEXT plan it now picks runs in about 150 ms.The
fulltext_index_tikvintegration result is re-recorded with the counted estimates.Check List
Tests
Some
cardinalitytests need failpoints; run them withtools/check/failpoint-go-test.sh.Side effects
Documentation
Release note
🤖 Generated with Claude Code