diff --git a/TOC-ai.md b/TOC-ai.md index 4ba8332a38b6d..efcd75df5c17e 100644 --- a/TOC-ai.md +++ b/TOC-ai.md @@ -189,6 +189,11 @@ - [Vector Data Types](/ai/reference/vector-search-data-types.md) - [Vector Functions and Operators](/ai/reference/vector-search-functions-and-operators.md) -- [Vector Search Index](/ai/reference/vector-search-index.md) -- [Vector Search Performance Tuning](/ai/reference/vector-search-improve-performance.md) -- [Vector Search Limitations](/ai/reference/vector-search-limitations.md) +- Vector Search + - [Vector Search Index](/ai/reference/vector-search-index.md) + - [Vector Search Performance Tuning](/ai/reference/vector-search-improve-performance.md) + - [Vector Search Limitations](/ai/reference/vector-search-limitations.md) +- Full-Text Search + - [Full-Text Search Index](/ai/reference/full-text-search-index.md) + - [Full-Text Search Functions](/ai/reference/full-text-search-functions-tidb.md) + - [Full-Text Search Limitations](/ai/reference/full-text-search-limitations.md) diff --git a/ai/guides/fulltext-search-with-pytidb.md b/ai/guides/fulltext-search-with-pytidb.md index 63eef8f2b9a2d..881d3f3c61f5b 100644 --- a/ai/guides/fulltext-search-with-pytidb.md +++ b/ai/guides/fulltext-search-with-pytidb.md @@ -19,6 +19,10 @@ Before you begin, ensure you have the following: - **Python (>=3.10)**: Install [Python](https://www.python.org/downloads/) 3.10 or a later version. - **A {{{ .starter }}} instance**: You can create a free {{{ .starter }}} instance on [TiDB Cloud](https://tidbcloud.com/free-trial). + > **Note:** + > + > Currently, full-text search is in public preview and **available only on {{{ .starter }}}**. + ## How to run ### Step 1. Clone the `pytidb` repository diff --git a/ai/guides/vector-search-full-text-search-sql.md b/ai/guides/vector-search-full-text-search-sql.md index cd437b395b82a..ffde031b438d7 100644 --- a/ai/guides/vector-search-full-text-search-sql.md +++ b/ai/guides/vector-search-full-text-search-sql.md @@ -16,17 +16,22 @@ The full-text search feature in TiDB provides the following capabilities: - **Order by relevance**: the search result can be ordered by relevance using the widely adopted [BM25 ranking](https://en.wikipedia.org/wiki/Okapi_BM25) algorithm. -- **Fully compatible with SQL**: all SQL features, such as pre-filtering, post-filtering, grouping, and joining, can be used with full-text search. +- **Multi-column search**: you can define multiple scored columns in one full-text index and search across them in a single query. BM25 scores are fused at the index level. + +- **Filter pushdown**: you can add filter columns (such as tenant IDs, status, and file paths) to a full-text index. Filter conditions on these columns are evaluated during the index scan, without accessing the table rows. + +- **Substring matching**: with the NGRAM parser, queries can match prefixes and substrings, such as matching `panic_handler` when searching for `panic`. + +- **SQL-native**: you can combine full-text search with filter conditions, aggregation, inner joins, and subqueries in ordinary SQL statements, without maintaining a separate search engine. > **Tip:** > -> For Python usage, see [Full-Text Search with Python](/ai/guides/vector-search-full-text-search-python.md). -> -> To use full-text search and vector search together in your AI apps, see [Hybrid Search](/ai/guides/vector-search-hybrid-search.md). +> - For Python usage, see [Full-Text Search with Python](/ai/guides/vector-search-full-text-search-python.md). +> - To use full-text search and vector search together in your AI apps, see [Hybrid Search](/ai/guides/vector-search-hybrid-search.md). ## Get started -Full-text search is still in the early stages, and we are continuously rolling it out to more customers. Currently, full-text search is only available on {{{ .starter }}} in the following regions: +Full-text search is still in the early stages, and we are continuously rolling it out to more customers. Currently, full-text search is **available only on {{{ .starter }}}** in the following regions: - AWS: `Oregon (us-west-2)`, `N. Virginia (us-east-1)`, `Tokyo (ap-northeast-1)`, `Frankfurt (eu-central-1)`, and `Singapore (ap-southeast-1)` @@ -65,6 +70,8 @@ CREATE TABLE stock_items( -- You might insert some data here. -- The full-text index can be created even if data is already in the table. +-- ADD_COLUMNAR_REPLICA_ON_DEMAND is optional. If you omit it, +-- make sure that a TiFlash replica is already created for the table. ALTER TABLE stock_items ADD FULLTEXT INDEX (title) WITH PARSER MULTILINGUAL ADD_COLUMNAR_REPLICA_ON_DEMAND; ``` @@ -74,40 +81,11 @@ The following parsers are accepted in the `WITH PARSER ` clause: - `MULTILINGUAL`: supports multiple languages, including English, Chinese, Japanese, and Korean. -### Manage full-text indexes - -When creating a full-text index, specifying an index name is optional. If you do not specify one, TiDB uses the name of the first indexed column as the index name by default. - -```sql --- Without specifying an index name, TiDB uses the first indexed column name ("title") as the index name -ALTER TABLE stock_items ADD FULLTEXT INDEX (title) WITH PARSER MULTILINGUAL; - --- Specifying an index name -ALTER TABLE stock_items ADD FULLTEXT INDEX ft_title (title) WITH PARSER MULTILINGUAL; -``` - -**View existing index names:** - -```sql --- The Key_name column shows the index name -SHOW INDEX FROM stock_items; - --- Or query INFORMATION_SCHEMA -SELECT INDEX_NAME, COLUMN_NAME, INDEX_TYPE -FROM INFORMATION_SCHEMA.STATISTICS -WHERE TABLE_SCHEMA = 'your_database' AND TABLE_NAME = 'stock_items'; -``` - -**Drop a full-text index:** - -```sql --- Use SHOW INDEX to confirm the index name first -ALTER TABLE stock_items DROP INDEX title; -``` +- `NGRAM`: builds character-level n-grams so that queries can match prefixes and substrings. See [The NGRAM parser](/ai/reference/full-text-search-index.md#the-ngram-parser) for parameters. #### Specify an index name -In both `CREATE TABLE` and `ALTER TABLE` statements, you can specify an index name after `FULLTEXT INDEX` or `FULLTEXT KEY`: +In both `CREATE TABLE` and `ALTER TABLE` statements, you can specify an index name after `FULLTEXT INDEX` or `FULLTEXT KEY`: ```sql -- Specifying a name in CREATE TABLE @@ -124,6 +102,20 @@ ALTER TABLE users ADD FULLTEXT INDEX ft_name (name) WITH PARSER STANDARD; CREATE FULLTEXT INDEX ft_name ON users (name) WITH PARSER STANDARD; ``` +#### Create a multi-column full-text index + +A full-text index can contain multiple scored columns. Searching across them in one query fuses the BM25 scores at the index level, which replaces scanning one single-column index per column and merging results with `UNION ALL`. + +```sql +ALTER TABLE articles ADD FULLTEXT INDEX ft_article (title, body) WITH PARSER MULTILINGUAL; + +SELECT * FROM articles + WHERE fts_match_word('database', title, body) + ORDER BY fts_match_word('database', title, body) DESC LIMIT 10; +``` + +Columns in one call are combined with OR semantics: a document matches if any of the columns matches the query. For AND semantics and more details, see [Multi-column search](/ai/reference/full-text-search-functions-tidb.md#multi-column-search). + ### Insert text data Inserting data into a table with a full-text index is identical to inserting data into any other tables. @@ -189,6 +181,10 @@ SELECT * FROM stock_items +------+---------------------------------------------------------------------------------------------------------------+ ``` +> **Note:** +> +> When you order results by `fts_match_word()`, the statement must include a `LIMIT` clause. To return the complete ranking, specify a large `LIMIT` value. See [Query limitations](/ai/reference/full-text-search-limitations.md#query-limitations). + **Example: count the number of documents matching the user query** ```sql @@ -204,9 +200,9 @@ SELECT COUNT(*) FROM stock_items #### Multi-word search: tokenization and query semantics -When you use `fts_match_word()`, the query string is tokenized according to the parser's rules, and each token is matched independently. +When you use `fts_match_word()`, the query string is tokenized according to the parser's rules, and each token is matched independently. -The STANDARD parser tokenizes strings into words using spaces and punctuation as delimiters. The MULTILINGUAL parser tokenizes strings according to language-specific segmentation rules. +The STANDARD parser tokenizes strings into words using spaces and punctuation as delimiters. The MULTILINGUAL parser tokenizes strings according to language-specific segmentation rules. ```sql -- This query is tokenized into two tokens: "Alice" and "Smith" @@ -221,15 +217,53 @@ SELECT * FROM users WHERE fts_match_word('Alice Smith', name); SELECT * FROM users WHERE fts_match_word('Alice Smith', name); ``` -A common misconception is that `fts_match_word('Alice X', name)` treats `"Alice X"` as a single entity for exact matching. In reality, it is tokenized into `Alice` and `X`, using OR semantics. Because `X` is a very short query term, it can match many irrelevant documents. Avoid using very short query terms or single letters. +A common misconception is that `fts_match_word('Alice X', name)` treats `"Alice X"` as a single entity for exact matching. In reality, it is tokenized into `Alice` and `X`, using OR semantics. Because `X` is a very short query term, it can match many irrelevant documents. Avoid using very short query terms or single letters. + +> **Note:** +> +> TiDB full-text search does not support exact phrase matching, where all query tokens must appear consecutively and in the specified order. -> **Note:** -> -> TiDB full-text search does not support exact phrase matching, where all query tokens must appear consecutively and in the specified order. +#### Prefix and substring search -#### Prefix search +To match prefixes or substrings, use a full-text index with the `NGRAM` parser. To match path prefixes such as `/src/`, use a filter column with the `path_hierarchy` attribute. See [Filter pushdown](#filter-pushdown). -**Not supported.** +The `STANDARD` and `MULTILINGUAL` parsers match complete tokens only. For partial-recall scenarios such as code search, create a full-text index with the `NGRAM` parser to match prefixes and substrings: + +```sql +ALTER TABLE code_files ADD FULLTEXT INDEX idx_fts_ngram (content_text) + WITH PARSER NGRAM(min_gram=3, max_gram=3); + +-- Matches HandleRequest, RequestHandler, and handle_error +SELECT /*+ USE_INDEX(code_files, idx_fts_ngram) */ * +FROM code_files + WHERE fts_match_word('handle', content_text) + ORDER BY fts_match_word('handle', content_text) DESC LIMIT 10; +``` + +A table can have multiple full-text indexes, and the same column can participate in several of them with different parsers. To search a column with a specific parser, follow the column with a `WITH PARSER parser_name` clause in the query. Alternatively, when each parser has its own index, select the index with the `USE_INDEX` hint, because the hinted index determines the parser and therefore the result set. Without either, the optimizer selects an index automatically and does not compare parsers. For parameters and query semantics, see [The NGRAM parser](/ai/reference/full-text-search-index.md#the-ngram-parser), [Select a parser for a scored column](/ai/reference/full-text-search-functions-tidb.md#select-a-parser-for-a-scored-column), and [Choose a full-text index at query time](/ai/reference/full-text-search-functions-tidb.md#choose-a-full-text-index-at-query-time). + +#### Filter pushdown + +In addition to scored columns, a full-text index can contain filter columns. Filter conditions on these columns are evaluated during the index scan, so you get correct scoped Top-K results instead of filtering after a global Top-K. Filter columns are defined with the column-property syntax: + +```sql +ALTER TABLE files ADD FULLTEXT INDEX idx_fts ( + content_text WITH (multilingual), + path WITH (exact, path_hierarchy), + ext WITH (exact) +); + +SELECT * FROM files + WHERE fts_match_word('database', content_text) + AND path LIKE '/src/%' + AND ext IN ('go', 'rs') + ORDER BY fts_match_word('database', content_text) DESC LIMIT 10; +``` + +- The `exact` attribute supports `=` and `IN` matching during the index scan. It is suitable for tenant IDs, status, tags, and other low-cardinality columns. +- The `path_hierarchy` attribute supports hierarchical prefix matching such as `path LIKE '/src/%'`, where the prefix aligns with the `/` delimiter boundary. + +For the full attribute reference, syntax rules, and pushdown limitations, see [Full-Text Search Index](/ai/reference/full-text-search-index.md) and [Filter pushdown limitations](/ai/reference/full-text-search-limitations.md#filter-pushdown-limitations). #### Effect of repeated terms on relevance scores @@ -244,7 +278,7 @@ In this example, a document matching `Alice` receives twice the weight contribut #### Relevance scoring algorithm -TiDB full-text search uses the **BM25Tantivy** algorithm to calculate relevance scores. This algorithm is a variant of the classic BM25 (Okapi BM25) algorithm that uses Count-Min Sketch to approximate document frequency (DF) for improved performance. +TiDB full-text search uses the **BM25Tantivy** algorithm to calculate relevance scores. This algorithm is a variant of the classic BM25 (Okapi BM25) algorithm that uses Count-Min Sketch to approximate document frequency (DF) for improved performance. **BM25 formula (standard form):** @@ -267,9 +301,40 @@ TiDB's implementation uses fixed values of `k1 = 1.2` and `b = 0.75`, which are The returned score is a non-negative floating-point number. A higher value indicates higher relevance to the query. Scores are not directly comparable across different datasets. +## Manage full-text indexes + +When creating a full-text index, specifying an index name is optional. If you do not specify one, TiDB uses the name of the first indexed column as the index name by default. + +```sql +-- Without specifying an index name, TiDB uses the first indexed column name ("title") as the index name +ALTER TABLE stock_items ADD FULLTEXT INDEX (title) WITH PARSER MULTILINGUAL; + +-- Specifying an index name +ALTER TABLE stock_items ADD FULLTEXT INDEX ft_title (title) WITH PARSER MULTILINGUAL; +``` + +### View existing index names + +```sql +-- The Key_name column shows the index name +SHOW INDEX FROM stock_items; + +-- Or query INFORMATION_SCHEMA +SELECT INDEX_NAME, COLUMN_NAME, INDEX_TYPE +FROM INFORMATION_SCHEMA.STATISTICS +WHERE TABLE_SCHEMA = 'your_database' AND TABLE_NAME = 'stock_items'; +``` + +### Drop a full-text index + +```sql +-- Use SHOW INDEX to confirm the index name first +ALTER TABLE stock_items DROP INDEX title; +``` + ## Advanced example: Join search results with other tables -You can combine full-text search with other SQL features such as joins and subqueries. +You can combine full-text search with other SQL features such as inner joins and subqueries. Assume you have a `users` table and a `tickets` table, and want to find tickets created by authors based on a full-text search of their names: @@ -298,7 +363,7 @@ You can use a subquery to find matching user IDs based on the author's name, and ```sql SELECT t.title AS TICKET_TITLE, u.id AS AUTHOR_ID, u.name AS AUTHOR_NAME FROM tickets t -LEFT JOIN users u ON t.author_id = u.id +INNER JOIN users u ON t.author_id = u.id WHERE t.author_id IN ( SELECT id FROM users @@ -316,6 +381,9 @@ WHERE t.author_id IN ## See also - [Hybrid Search](/ai/guides/vector-search-hybrid-search.md) +- [Full-Text Search Index](/ai/reference/full-text-search-index.md) +- [Full-Text Search Functions](/ai/reference/full-text-search-functions-tidb.md) +- [Full-Text Search Limitations](/ai/reference/full-text-search-limitations.md) ## Feedback & help diff --git a/ai/reference/full-text-search-functions-tidb.md b/ai/reference/full-text-search-functions-tidb.md new file mode 100644 index 0000000000000..49c1b379c4f0e --- /dev/null +++ b/ai/reference/full-text-search-functions-tidb.md @@ -0,0 +1,299 @@ +--- +title: TiDB Full-Text Search Functions +summary: Learn how to search text with the FTS_MATCH_WORD() function, including multi-column queries, parser selection, and index choice. +--- + +# TiDB Full-Text Search Functions + +This document describes the `FTS_MATCH_WORD()` function for full-text search in TiDB, including multi-column search, multi-word queries, and how to select the parser and the full-text index that a query runs on. + +For how to create the full-text indexes that these functions use, see [Full-Text Search Index](/ai/reference/full-text-search-index.md). + +> **Note:** +> +> Currently, full-text search is in public preview and **available only on {{{ .starter }}}**. + +## FTS_MATCH_WORD() + +`FTS_MATCH_WORD()` performs a keyword search against one or more scored columns of a full-text index and returns a BM25 relevance score. + +``` +FTS_MATCH_WORD('query', col [WITH PARSER parser_name] [, col [WITH PARSER parser_name]...]) +``` + +| Parameter | Description | +| :-- | :-- | +| `query` | The search text. Each scored column tokenizes it with the parser selected for that column. | +| `col [WITH PARSER parser_name]` | A scored column, optionally followed by `WITH PARSER parser_name` to select the tokenizer for that column. The column can be one of the scored columns of a full-text index. | + +To search one column with more than one parser, declare several parser attributes on that column in the index definition and select one per query with `WITH PARSER`. See [Select a parser for a scored column](#select-a-parser-for-a-scored-column). + +Filter conditions on filter columns are written outside the function, as independent `WHERE` conditions: + +```sql +SELECT * FROM t +WHERE FTS_MATCH_WORD('database', content_text) + AND path LIKE '/src/%' + AND name = 'main.go' +ORDER BY FTS_MATCH_WORD('database', content_text) DESC +LIMIT 10; +``` + +If a column in `col [, col...]` does not exist in the table, TiDB reports `ERROR 1054 (42S22): Unknown column 'xxx' in 'fts_match_word'`. + +## Multi-column search + +You can search multiple scored columns in a single call. Columns are combined with **OR** semantics: `FTS_MATCH_WORD('query', col1, col2)` matches documents where `col1` matches the query or `col2` matches the query, and BM25 scores are fused at the index level. + +```sql +SELECT * FROM t +WHERE FTS_MATCH_WORD('database', content_text, description) +ORDER BY FTS_MATCH_WORD('database', content_text, description) DESC +LIMIT 10; +``` + +A single call is the way to search several columns at once, because multiple calls in one `WHERE` clause can only be combined with `OR`. To require all columns to match (**AND** semantics), intersect the row set of one call per column: + +```sql +SELECT id FROM t WHERE FTS_MATCH_WORD('database', content_text) +INTERSECT +SELECT id FROM t WHERE FTS_MATCH_WORD('database', description); +``` + +In a multi-column query, each column is tokenized by the parser selected for that column, and the BM25 scores are fused at the index level. A query can also use a subset of the scored columns of an index. For example, if an index covers `content_text` and `description`, `FTS_MATCH_WORD('query', content_text)` still uses that index. + +## Multi-word query semantics + +When the query string contains multiple words, it is tokenized according to the parser rules, and each token is matched independently. `FTS_MATCH_WORD()` uses **OR** semantics across tokens: a document matches if it contains any of the tokens, and matching more tokens increases the relevance score. + +```sql +-- This query is tokenized into two tokens: "Alice" and "Smith". +-- It returns all rows where name contains "Alice" or "Smith" or both. +SELECT * FROM users WHERE FTS_MATCH_WORD('Alice Smith', name); +``` + +Multiple calls combined with `OR` are merged into one index scan: + +```sql +SELECT * FROM t +WHERE FTS_MATCH_WORD('database', content_text) + OR FTS_MATCH_WORD('vector', content_text); +``` + +Combining multiple calls with `AND` at the top level of `WHERE` is not supported. TiDB reports the following error, even when the two calls use different words or different columns: + +``` +ERROR 1221 (HY000): Currently 'FTS_MATCH_WORD()' must be used alone. It cannot be placed inside any other function or expression as a parameter, or used multiple times. +``` + +To require multiple words to match (**AND** semantics), or to exclude documents that match a word (**NOT** semantics), use a compound statement: + +```sql +-- AND: both words match +SELECT id FROM t WHERE FTS_MATCH_WORD('database', content_text) +INTERSECT +SELECT id FROM t WHERE FTS_MATCH_WORD('vector', content_text); + +-- NOT: matches the first word but not the second +SELECT id FROM t WHERE FTS_MATCH_WORD('database', content_text) +EXCEPT +SELECT id FROM t WHERE FTS_MATCH_WORD('obsolete', content_text); +``` + +To keep the table columns in the output, put the compound statement in a subquery: + +```sql +SELECT * FROM t +WHERE id IN ( + SELECT id FROM t WHERE FTS_MATCH_WORD('database', content_text) + INTERSECT + SELECT id FROM t WHERE FTS_MATCH_WORD('vector', content_text) +); +``` + +## Query semantics with the NGRAM parser + +When the matched index uses the `NGRAM` parser, `FTS_MATCH_WORD()` performs substring matching. The query string is split into n-grams using the same `min_gram` and `max_gram` settings as the index, and the n-grams are combined with **AND** semantics by default. + +For example, with `min_gram=max_gram=3`, searching `apple` is equivalent to searching `app` AND `ppl` AND `ple`: all n-grams must match in the same document. + +```sql +SELECT /*+ USE_INDEX(t, idx_fts_ngram) */ * +FROM t +WHERE FTS_MATCH_WORD('handle', content_text); +-- Matches HandleRequest, RequestHandler, and handle_error +``` + +To use OR semantics between n-grams, combine multiple `FTS_MATCH_WORD()` calls with `OR`: + +```sql +SELECT * FROM t +WHERE FTS_MATCH_WORD('app', content_text) + OR FTS_MATCH_WORD('ppl', content_text); +``` + +## Relevance scoring + +`FTS_MATCH_WORD()` returns a BM25 relevance score. The score is a non-negative floating-point number. A higher value indicates higher relevance. Scores are not directly comparable across different datasets. + +If the query string contains repeated terms, the term frequency of that term is counted multiple times in scoring. For example, in `FTS_MATCH_WORD('Alice alice bob', name)`, the term `Alice` contributes twice the weight of `bob`. This is expected BM25 behavior. + +For the full scoring formula and parameters, see [Relevance scoring algorithm](/ai/guides/vector-search-full-text-search-sql.md#relevance-scoring-algorithm). + +## Select a parser for a scored column + +A scored column can carry more than one parser attribute in an index definition. To choose which one a query uses, follow that column with a `WITH PARSER parser_name` clause inside `FTS_MATCH_WORD()`: + +```sql +ALTER TABLE t ADD FULLTEXT INDEX idx_fts ( + content_text WITH (multilingual, ngram(min_gram=3, max_gram=3)) +); +``` + +```sql +-- Substring matching: the NGRAM parser matches 'hand' inside 'HandleRequest' +SELECT * FROM t +WHERE FTS_MATCH_WORD('hand', content_text WITH PARSER ngram); + +-- Complete token matching: the MULTILINGUAL parser matches whole tokens only +SELECT * FROM t +WHERE FTS_MATCH_WORD('database', content_text WITH PARSER multilingual); + +-- Without the clause, the column uses the first parser attribute in the index +-- definition, which is MULTILINGUAL here +SELECT * FROM t +WHERE FTS_MATCH_WORD('database', content_text); +``` + +The clause applies only to the column that precedes it, and it takes a parser name only. Parameters such as `WITH PARSER ngram(min_gram=5)` are not accepted, because gram sizes belong to the index definition. If the column has no attribute of the named parser, TiDB returns an error instead of falling back to another parser, so that you do not silently get results from a tokenizer you did not ask for. + +In a multi-column call, each column can name its own parser, and the parsers of all scored columns must be satisfiable by the same index. When no index covers the combination, TiDB returns an error rather than scanning one index per column and merging scores outside the index. + +```sql +ALTER TABLE t ADD FULLTEXT INDEX idx_fts_multi ( + content_text WITH (multilingual, ngram(min_gram=3, max_gram=3)), + description WITH (multilingual, ngram(min_gram=3, max_gram=3)), + path WITH (exact, path_hierarchy) +); + +-- One index scan: content_text uses NGRAM, description uses MULTILINGUAL +SELECT * FROM t +WHERE FTS_MATCH_WORD('hand', content_text WITH PARSER ngram, description WITH PARSER multilingual) + AND path LIKE '/src/%'; +``` + +A column that does not name a parser uses the first compatible parser attribute of the index it lands on. It does not inherit a parser named for another column in the same call. + +The clause is valid only on scored columns. Parser attributes and filter attributes cannot coexist on one column, so `WITH PARSER` on an `exact` or `path_hierarchy` column is an error. + +Alternatively, keep one parser per full-text index and select the index with the `USE_INDEX` hint. This is useful when the parsers need different parameters or different filter columns: + +```sql +ALTER TABLE t ADD FULLTEXT INDEX idx_fts_ml (content_text) WITH PARSER MULTILINGUAL; +ALTER TABLE t ADD FULLTEXT INDEX idx_fts_ngram (content_text) + WITH PARSER NGRAM(min_gram=3, max_gram=3); +``` + +```sql +SELECT /*+ USE_INDEX(t, idx_fts_ngram) */ * FROM t +WHERE FTS_MATCH_WORD('hand', content_text); + +SELECT /*+ USE_INDEX(t, idx_fts_ml) */ * FROM t +WHERE FTS_MATCH_WORD('database', content_text); +``` + +> **Note:** +> +> Both `WITH PARSER` and `USE_INDEX` change the result set, not just the execution plan, because the tokenizer decides which documents match. When a scored column offers more than one parser, name the parser with `WITH PARSER` or name the index with `USE_INDEX` rather than relying on automatic selection. See [Automatic index selection](#automatic-index-selection). + +## Choose a full-text index at query time + +When a table has multiple full-text indexes, you can control which index is used: + +### USE_INDEX: specify an index explicitly + +```sql +-- Use the NGRAM index (substring matching) +SELECT /*+ USE_INDEX(t, idx_fts_ngram) */ * +FROM t WHERE FTS_MATCH_WORD('handle', content_text); + +-- Use the MULTILINGUAL index (complete token matching) +SELECT /*+ USE_INDEX(t, idx_fts_ml) */ * +FROM t WHERE FTS_MATCH_WORD('database', content_text); +``` + +`USE_INDEX` semantics: + +| Scenario | Behavior | +| :-- | :-- | +| The indexes differ only in parser | The hint selects the index, which selects the parser, so the result set changes. To choose a parser without choosing an index, use `WITH PARSER`. | +| The indexes use the same parser | A pure execution-path choice. The result set is unchanged. | +| A scored column names a parser that the hinted index does not have | The hint is ignored, and the optimizer selects an index that satisfies the parsers named by all scored columns. | +| Some scored columns name a parser and others do not | Named columns use the named parser. Unnamed columns use the first compatible parser attribute of the index that is selected. | +| The specified index does not exist | The hint is silently ignored, and the optimizer selects an index automatically. | +| The specified index does not cover a column that the query uses | TiDB reports the index and the column in the error, for example: `ERROR 1221 (HY000): full-text search index idx_fts_ng does not cover column test.docs.ext`. | + +### IGNORE_INDEX: exclude an index + +```sql +SELECT /*+ IGNORE_INDEX(t, idx_fts_ngram) */ * +FROM t WHERE FTS_MATCH_WORD('handle', content_text); +``` + +If `IGNORE_INDEX` excludes every full-text index that could serve the query, TiDB returns an error instead of scanning the table: + +``` +ERROR 1221 (HY000): full text search can only be used with a matching current TiFlash full-text index path +``` + +### Automatic index selection + +Without hints, the optimizer selects a full-text index by the following priorities: + +| Priority | Rule | +| :-- | :-- | +| 1 | Column coverage: prefer the index whose scored columns overlap most with the columns in the query. | +| 2 | Filter column coverage: prefer the index that matches more filter conditions in the `WHERE` clause. | +| 3 | Index size: prefer the smaller index to reduce scan cost. | + +These priorities do not compare parsers, so they apply only when no scored column names a parser. When one column offers more than one parser and the query names none of them, the selected index decides the matching behavior without any warning. Name the parser with `WITH PARSER`, or name the index with `USE_INDEX`. + +A query that uses `FTS_MATCH_WORD()` always runs on a full-text index. If no full-text index covers the queried columns, TiDB returns an error rather than falling back to a table scan or a regular index scan. + +## Supported query patterns + +- Single-table queries with filter conditions, aggregation, ordering, and pagination: + + ```sql + SELECT category, COUNT(*) FROM t + WHERE FTS_MATCH_WORD('query', content_text) GROUP BY category; + + SELECT * FROM t WHERE FTS_MATCH_WORD('query', content_text) + ORDER BY FTS_MATCH_WORD('query', content_text) DESC LIMIT 10; + ``` + + Ordering by `FTS_MATCH_WORD()` requires a `LIMIT` clause. Without one, TiDB reports: + + ``` + ERROR 1221 (HY000): 'FTS_MATCH_WORD()' in ORDER BY without a LIMIT clause is not supported, try specify a very large LIMIT as a workaround + ``` + + To return the complete ranking in a single statement, specify a large `LIMIT` value. Ordering by a regular column needs no `LIMIT`. + +- `INNER JOIN`, where the full-text search runs on the driving table and the join runs on the result set: + + ```sql + SELECT a.*, b.* FROM articles a + INNER JOIN authors b ON a.author_id = b.id + WHERE FTS_MATCH_WORD('database', a.content_text); + ``` + +- `UNION`, `UNION ALL`, `EXCEPT`, and `INTERSECT`. Each branch matches its full-text index independently, and the branch results are combined by the set operator. The outer `ORDER BY` and `LIMIT` of the compound statement run after the set operation and are not pushed into the full-text scans. + +For restrictions such as `ORDER BY` limitations and join support, see [Full-Text Search Limitations](/ai/reference/full-text-search-limitations.md). + +## See also + +- [Full-Text Search with SQL](/ai/guides/vector-search-full-text-search-sql.md) +- [Full-Text Search Index](/ai/reference/full-text-search-index.md) +- [Full-Text Search Limitations](/ai/reference/full-text-search-limitations.md) diff --git a/ai/reference/full-text-search-index.md b/ai/reference/full-text-search-index.md new file mode 100644 index 0000000000000..4bfcd4e403f80 --- /dev/null +++ b/ai/reference/full-text-search-index.md @@ -0,0 +1,318 @@ +--- +title: Full-Text Search Index +summary: Learn how to create and manage full-text indexes in TiDB, including syntax modes, column attributes, parsers, and DDL restrictions. +--- + +# Full-Text Search Index + +This document describes how to create and manage full-text indexes in TiDB, including the two index definition syntaxes, column attributes, parsers, multiple indexes on one table, and DDL restrictions on indexed columns and tables. + +To run full-text queries against a full-text index, see [Full-Text Search Functions](/ai/reference/full-text-search-functions-tidb.md). + +> **Note:** +> +> Currently, full-text search is in public preview and **available only on {{{ .starter }}}**. +## Create a full-text index + +You can create a full-text index on a new table with `CREATE TABLE`, or add one to an existing table with `ALTER TABLE`. TiDB supports two definition syntaxes: + +- [Syntax sugar mode](#syntax-sugar-mode): `(col) WITH PARSER parser_name`. A simple form for single-purpose indexes. +- [Column-property mode](#column-property-mode): `col WITH (attribute1, attribute2(param=value))`. Configures tokenizers and filter attributes per column. + +The two modes are mutually exclusive within one index definition. Mixing them in the same `FULLTEXT INDEX` definition returns an error. + +### Syntax sugar mode + +```sql +ALTER TABLE t ADD FULLTEXT INDEX idx_fts (content_text) WITH PARSER MULTILINGUAL; +``` + +| Clause | Description | +| :-- | :-- | +| `(content_text)` | The scored column. It participates in the BM25 inverted index and relevance scoring. | +| `WITH PARSER MULTILINGUAL` | The tokenizer (parser) used to tokenize text for indexing and querying. | + +Accepted parsers in the `WITH PARSER ` clause: + +- `STANDARD`: fast, works for English content, splitting words by spaces and punctuation. All text is lowercased for indexing and search (case-insensitive matching). +- `MULTILINGUAL`: supports multiple languages, including English, Chinese, Japanese, and Korean. Case-insensitive for both indexing and querying. +- `NGRAM`: a character-level n-gram tokenizer that supports substring matching. See [The NGRAM parser](#the-ngram-parser) for parameters. + +```sql +ALTER TABLE t ADD FULLTEXT INDEX idx_fts_ngram (content_text) + WITH PARSER NGRAM(min_gram=3, max_gram=3); +``` + +Syntax sugar mode is equivalent to column-property mode with a single parser attribute: `(col) WITH PARSER MULTILINGUAL` equals `col WITH (multilingual)`. Syntax sugar mode does not support filter columns. To define filter columns, use column-property mode. + +> **Note:** +> +> - Specifying an index name is optional in both syntax sugar mode and column-property mode. If you omit it, TiDB generates a name for the index. See [Index naming](#index-naming). +> - The `ADD_COLUMNAR_REPLICA_ON_DEMAND` clause is optional. When specified, TiDB creates a TiFlash replica for the table on demand. If you omit it, make sure that a TiFlash replica is already created for the table before you use full-text search. + +### Column-property mode + +In column-property mode, each column declares one or more attributes in a `WITH (...)` clause: + +```sql +ALTER TABLE t ADD FULLTEXT INDEX idx_fts ( + content_text WITH (multilingual), + description WITH (multilingual), + path WITH (exact, path_hierarchy), + name WITH (exact), + ext WITH (exact) +); +``` + +Attributes fall into two categories: + +- **Parser attributes**: `multilingual` and `ngram`. Columns with parser attributes are scored columns that participate in BM25 scoring. +- **Filter attributes**: `exact` and `path_hierarchy`. Columns with filter attributes are filter columns. Filter conditions on these columns are evaluated during the full-text index scan, without accessing the table rows. + +Rules for column attributes: + +- A column can have multiple attributes, separated by commas inside `WITH (...)`. For example, `path WITH (exact, path_hierarchy)` makes the column support both equality filters and path prefix filters. +- A scored column can declare more than one parser attribute, such as `content_text WITH (multilingual, ngram(...))`. A query selects one of them with the `WITH PARSER` clause that follows the column in `FTS_MATCH_WORD()`. Without the clause, the column uses the first parser attribute in the index definition. See [Select a parser for a scored column](/ai/reference/full-text-search-functions-tidb.md#select-a-parser-for-a-scored-column). +- The same type of parser can appear only once per column. You cannot define two parsers of the same type with different parameters on one column. +- Parser attributes and filter attributes cannot coexist on the same column. A column is either a scored column or a filter column, not both. +- Attribute parameters have default values. You can omit any parameter to use its default. See [Column attribute reference](#column-attribute-reference). +- Filter attribute columns inherit the collation of the corresponding TiDB column. Case sensitivity of filter matching is determined by the column collation. For example, with `utf8mb4_bin` filters are case-sensitive; with `utf8mb4_general_ci` they are case-insensitive. + +#### Column attribute reference + +| Attribute | Parameters | Default values | Description | +| :-- | :-- | :-- | :-- | +| `multilingual` | None | - | Language-aware tokenizer that matches complete tokens. Case-insensitive. | +| `ngram` | `min_gram`, `max_gram`, `granularity`, `lower_case` | `min_gram=3`, `max_gram=3`, `granularity='word'`, `lower_case=true` | Character-level n-gram tokenizer that supports prefix, infix, and suffix substring matching. See [The NGRAM parser](#the-ngram-parser). | +| `exact` | None | - | Exact-value matching using inverted posting lists. Supports `=` and `IN`. Used for tenant IDs, status, tags, and other low-cardinality filters. | +| `path_hierarchy` | `delimiter` | `delimiter='/'` | Hierarchical prefix matching for path-like values. Supports prefix matching such as `col LIKE '/src/%'`. The prefix must align with a delimiter boundary. | + +To customize the delimiter of `path_hierarchy`: + +```sql +ALTER TABLE t ADD FULLTEXT INDEX idx_fts ( + content_text WITH (multilingual), + path WITH (exact, path_hierarchy(delimiter='$')) +); +``` + +## The NGRAM parser + +The `NGRAM` parser builds character-level n-grams so that queries can match substrings. For example, searching `handle` matches documents containing `HandleRequest`, `RequestHandler`, or `handle_error`, which complete-token parsers such as `MULTILINGUAL` cannot match. + +| Parameter | Type | Valid values | Default | Description | +| :-- | :-- | :-- | :-- | :-- | +| `min_gram` | INTEGER | [2, `max_gram`] | `3` | The minimum n-gram length. | +| `max_gram` | INTEGER | [`min_gram`, 5] | `3` | The maximum n-gram length. | +| `granularity` | STRING | `'word'` or `'char'` | `'word'` | Controls how n-grams are generated. See below. | +| `lower_case` | BOOLEAN | `true` or `false` | `true` | Whether text is lowercased at indexing and query time. `true` means case-insensitive matching; `false` preserves the original case. | + +The `granularity` parameter controls n-gram generation: + +| granularity | Behavior | Output for `hello world` (`min_gram=max_gram=3`) | +| :-- | :-- | :-- | +| `word` (default) | Tokenizes the text into words first, then applies a character sliding window inside each word. Avoids meaningless n-grams crossing word boundaries. | `hel`, `ell`, `llo`, `wor`, `orl`, `rld` | +| `char` | Applies a character sliding window over the entire text, ignoring word or space boundaries. Suitable for languages without space-separated words, or for matching across symbols. | `hel`, `ell`, `llo`, `lo_`, `o_w`, `_wo`, `wor`, `orl`, `rld` | + +Examples: + +```sql +-- Defaults: 3-gram, word granularity, case-insensitive +WITH PARSER NGRAM(min_gram=3, max_gram=3) + +-- Character-level sliding window (includes spaces and symbols) +WITH PARSER NGRAM(min_gram=3, max_gram=3, granularity='char') + +-- Case-sensitive matching +WITH PARSER NGRAM(min_gram=3, max_gram=3, lower_case=false) + +-- All parameters can be omitted to use defaults +WITH PARSER NGRAM +``` + +### MULTILINGUAL versus NGRAM + +| Aspect | MULTILINGUAL | NGRAM | +| :-- | :-- | :-- | +| Tokenization | Language-aware segmentation | Character-level sliding window | +| Matching scope | Complete tokens | Prefix / infix / suffix substrings | +| Recall | Precise | Loose | +| Index size | Moderate | Larger | +| Suitable scenarios | Complete keyword search | Partial-recall and code snippet search | + +You can build both a `MULTILINGUAL` index and an `NGRAM` index on the same column and route queries to either one at query time. See [Multiple indexes on one table](#multiple-indexes-on-one-table). + +## Multi-column full-text indexes + +A full-text index can contain multiple scored columns. BM25 scores are fused at the index level in a single scan, which replaces the pattern of scanning one index per column and merging results with `UNION ALL` in the application. + +```sql +-- Syntax sugar mode: all columns share the same parser +ALTER TABLE t ADD FULLTEXT INDEX idx_fts_multi + (content_text, description) WITH PARSER MULTILINGUAL; + +-- Column-property mode: scored columns and filter columns in one index +ALTER TABLE t ADD FULLTEXT INDEX idx_fts_multi ( + content_text WITH (multilingual), + description WITH (multilingual), + path WITH (exact, path_hierarchy), + name WITH (exact) +); +``` + +To search across multiple scored columns, list them in the `FTS_MATCH_WORD()` call. For details, see [Full-Text Search Functions](/ai/reference/full-text-search-functions-tidb.md). + +## Multiple indexes on one table + +A table can have multiple full-text indexes. The same column can participate in multiple full-text indexes, each with a different parser. A single index can also declare several parser attributes on one column, which avoids duplicating the filter columns of that index. + +```sql +ALTER TABLE t ADD FULLTEXT INDEX idx_fts_ml + (content_text) WITH PARSER MULTILINGUAL; + +ALTER TABLE t ADD FULLTEXT INDEX idx_fts_ng + (content_text) WITH PARSER NGRAM(min_gram=3, max_gram=3); +``` + +At query time, select the index with the `USE_INDEX` or `IGNORE_INDEX` optimizer hint, or select the parser with the `WITH PARSER` clause in `FTS_MATCH_WORD()`. When the available parsers are not named by the query, automatic index selection does not compare them, so the matching behavior of the query is not what you intend. See [Select a parser for a scored column](/ai/reference/full-text-search-functions-tidb.md#select-a-parser-for-a-scored-column) and [Choose a full-text index at query time](/ai/reference/full-text-search-functions-tidb.md#choose-a-full-text-index-at-query-time). + +### Index naming + +If you do not specify an index name, TiDB generates one automatically: + +1. By default, TiDB uses the name of the first indexed column as the index name. +2. If that name already exists, TiDB tries the `_2`, `_3`, and subsequent suffixes until the name is unique. +3. If the first indexed column name is the reserved word `PRIMARY`, TiDB starts from `primary_2`. + +The generated name can be referenced in the `USE_INDEX` hint. + +## View and drop full-text indexes + +`SHOW CREATE TABLE` outputs the full index definition, including the parser and per-column attributes: + +```sql +SHOW CREATE TABLE t; +``` + +``` +CREATE TABLE `t` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `content_text` text DEFAULT NULL, + `description` text DEFAULT NULL, + `path` varchar(512) DEFAULT NULL, + `name` varchar(256) DEFAULT NULL, + PRIMARY KEY (`id`), + FULLTEXT KEY `idx_fts_multi` (`content_text` WITH (multilingual), `description` WITH (multilingual), `path` WITH (exact, path_hierarchy), `name` WITH (exact)) +); +``` + +In column-property mode, every column's parser and filter attributes are shown in the `WITH (...)` clause after the column name. + +`SHOW INDEX` reports `FULLTEXT` in the `Index_type` column, compatible with MySQL: + +```sql +SHOW INDEX FROM t WHERE Key_name = 'idx_fts'; +``` + +You can also query `INFORMATION_SCHEMA`: + +- `INFORMATION_SCHEMA.STATISTICS`: `INDEX_TYPE` returns `FULLTEXT`. +- `INFORMATION_SCHEMA.TIDB_INDEXES`: `index_type` returns `FULLTEXT`. + +Full-text indexes do not report usage statistics, so they do not appear in `INFORMATION_SCHEMA.TIDB_INDEX_USAGE`. See [Observability limitations](/ai/reference/full-text-search-limitations.md#observability-limitations). + +To drop a full-text index: + +```sql +ALTER TABLE t DROP INDEX idx_fts; +``` + +## DDL restrictions + +Columns that participate in a full-text index are subject to DDL restrictions. Common table-level operations on a table that contains a full-text index are not blocked, but creating and maintaining a full-text index has its own restrictions. + +### Restrictions on indexed columns + +Full-text indexes validate scored columns and filter columns in the same way, because both belong to the indexed column set. The two kinds of columns differ only in the column types that their parser or attribute accepts. See [Parser and column type compatibility](#parser-and-column-type-compatibility). + +| DDL operation | Allowed | Notes | +| :-- | :-- | :-- | +| `DROP COLUMN` | No | TiDB rejects the statement when a full-text index covers the column, even if the index contains only that column. Drop the full-text index first, and then drop the column. You cannot combine `DROP INDEX` and `DROP COLUMN` in one `ALTER TABLE` statement, because TiDB validates every clause against the original schema. | +| `RENAME COLUMN` | Yes | TiDB updates the column name in the index automatically, and you do not need to rebuild the index. Renaming a column with `CHANGE COLUMN` while keeping the same type is also allowed. | +| `MODIFY COLUMN` or `CHANGE COLUMN` (no data rewrite) | Conditional | Allowed only when all four conditions in [Conditions for a type change](#conditions-for-a-type-change) are met. Typical examples are `VARCHAR(20)` to `VARCHAR(40)` and `INT` to `BIGINT`. | +| `MODIFY COLUMN` or `CHANGE COLUMN` (data rewrite required) | No | TiDB rejects changes such as reducing a length or a type range, `CHAR` to `VARCHAR`, `FLOAT` to `DOUBLE`, and conversions between signed and unsigned types. | +| `MODIFY COLUMN` or `CHANGE COLUMN` (type incompatible with the parser) | No | TiDB validates the new type against the parser that the column uses, even when the change does not rewrite data. For example, changing a column to `VARBINARY`, or to a `BINARY` collation, is rejected. | +| `ALTER COLUMN SET DEFAULT` and `ALTER COLUMN DROP DEFAULT` | Yes | No full-text index restriction applies. | +| Change the column collation | No | This is a general restriction for any indexed column and is not specific to full-text indexes. | +| Inline `FULLTEXT` column option in `MODIFY COLUMN` or `CHANGE COLUMN` | No | You cannot add a full-text index through a column definition. Use `ALTER TABLE ... ADD FULLTEXT INDEX` instead. | + +#### Conditions for a type change + +A `MODIFY COLUMN` or `CHANGE COLUMN` operation that does not rewrite data is allowed only when all of the following conditions are met: + +1. TiDB supports the type conversion. +2. The conversion does not require rewriting the column data. This is the key criterion, and it replaces a simple widening-versus-narrowing rule. +3. The new type is still compatible with the parser that is bound to the column. +4. The conversion does not trigger other general DDL restrictions, such as a collation change, a generated column dependency, or a partition column constraint. + +#### Common type changes + +| Type change | Supported | Reason | +| :-- | :-- | :-- | +| `VARCHAR(20)` to `VARCHAR(40)` | Yes | Expands the length without rewriting data. The column remains a non-binary string. | +| `CHAR(20)` to `CHAR(40)` | Yes | Expands the length within the same non-binary `CHAR` type without rewriting data. | +| `INT` to `BIGINT` | Yes | Expands the integer range without rewriting data. | +| `INT UNSIGNED` to `BIGINT UNSIGNED` | Yes | Expands the integer range without changing signedness. | +| `INT` to `BIGINT UNSIGNED` | No | Changes signedness, which requires a data rewrite. | +| `CHAR(20)` to `VARCHAR(40)` | No | Requires a data rewrite. | +| `FLOAT` to `DOUBLE` | No | Requires a data rewrite. | +| `VARCHAR(20)` to `VARCHAR(40) BINARY` | No | The new type is not compatible with a full-text string parser. | +| `VARCHAR(20)` to `VARBINARY(40)` | No | The new type is not compatible with a full-text string parser. | +| `VARCHAR(40)` to `VARCHAR(20)` | No | Reduces the length, which requires a data rewrite. | +| `INT` to `SMALLINT` | No | Narrows the type, which requires a data rewrite. | +| `TEXT` to `INT` | No | Changes the type across categories, which requires a data rewrite. | + +This table is not exhaustive. The four conditions in [Conditions for a type change](#conditions-for-a-type-change) are the authoritative criteria. When you modify any column of a multi-column full-text index, TiDB re-validates the whole column set of that index. + +#### Parser and column type compatibility + +| Parser or attribute | Allowed column types | +| :-- | :-- | +| `STANDARD`, `MULTILINGUAL`, `NGRAM`, and `path_hierarchy` | Non-binary string types only, which means a string type whose collation is not `binary`. | +| `exact` | Non-binary string types, or the following native types: `TINYINT`, `SMALLINT`, `MEDIUMINT`, `INT`, `BIGINT`, `BIT`, `YEAR`, `FLOAT`, `DOUBLE`, `DATE`, `DATETIME`, `TIMESTAMP`, `TIME`, and `ENUM`. `DECIMAL` is not supported. | + +### Restrictions on tables with full-text indexes + +TiDB applies no full-text-specific validation to the operations in the following table, and you do not need to drop the full-text index before you run them. + +| DDL operation | Allowed | Notes | +| :-- | :-- | :-- | +| `TRUNCATE TABLE` | Yes | No full-text index validation applies. | +| `DROP TABLE` | Yes | TiDB removes the full-text index together with the table. | +| `RENAME TABLE` and `ALTER TABLE ... RENAME TO` | Yes | The full-text index moves with the table. | +| `ADD COLUMN` | Yes | TiDB does not add the new column to an existing full-text index automatically. | +| `ADD COLUMN` with an inline `FULLTEXT` column option | Yes, with a warning | TiDB ignores the column option and returns a warning that the table type does not support full-text indexes. Use `ALTER TABLE ... ADD FULLTEXT INDEX` instead. | +| `ALTER TABLE ... SET TIFLASH REPLICA 0` | Yes | TiDB does not reject the statement because a full-text index exists. | +| `DROP INDEX` for a full-text index | Yes | You can combine this clause with other `DROP INDEX` clauses in one `ALTER TABLE` statement. TiDB reclaims the index data on the storage side asynchronously. | + +These operations are not the only table-level statements that affect a table with a full-text index. Full-text indexes do not support partitioned, temporary, or cached tables, so if you plan to convert a table that has a full-text index into one of these types, drop the index first and re-create it after the change. + +### Restrictions on index creation and maintenance + +The following restrictions apply when you create a full-text index or run maintenance statements. They are not table-level DDL blocks. + +| Operation | Allowed | Notes | +| :-- | :-- | :-- | +| Create a full-text index on a partitioned, temporary, or cached table | No | TiDB validates this restriction in both `CREATE TABLE` and `ALTER TABLE ... ADD FULLTEXT INDEX`. | +| Combine `ADD FULLTEXT INDEX` with other `ALTER TABLE` clauses | No | Full-text indexes do not support merged schema changes. Run `ADD FULLTEXT INDEX` as a standalone statement. | +| `ALTER INDEX ... INVISIBLE` | No | You cannot set a full-text index to invisible. `ALTER INDEX ... VISIBLE` is allowed. | +| `ADMIN CLEANUP INDEX` | No | Full-text indexes do not support cleanup. | +| `ADMIN CHECK TABLE` and `ADMIN CHECK INDEX` | Skipped | Full-text indexes do not participate in consistency checks. TiDB skips them and does not return an error. | + +For the full list of functional limitations, see [Full-Text Search Limitations](/ai/reference/full-text-search-limitations.md). + +## See also + +- [Full-Text Search with SQL](/ai/guides/vector-search-full-text-search-sql.md) +- [Full-Text Search Functions](/ai/reference/full-text-search-functions-tidb.md) +- [Full-Text Search Limitations](/ai/reference/full-text-search-limitations.md) diff --git a/ai/reference/full-text-search-limitations.md b/ai/reference/full-text-search-limitations.md new file mode 100644 index 0000000000000..c9cb5d6eb74df --- /dev/null +++ b/ai/reference/full-text-search-limitations.md @@ -0,0 +1,139 @@ +--- +title: Full-Text Search Limitations +summary: Learn the limitations of full-text search in TiDB, covering index definition, filter pushdown, query behavior, DML, DDL, and observability. +--- + +# Full-Text Search Limitations + +This document describes the known limitations of full-text search in TiDB. + +> **Note:** +> +> Currently, full-text search is in public preview and **available only on {{{ .starter }}}**. + +## Index limitations + +- In one full-text index definition, the syntax sugar mode `(col) WITH PARSER parser_name` and the column-property mode `col WITH (...)` are mutually exclusive. Mixing both modes in the same index definition returns an error. +- On a single column, the same type of parser can appear only once. You cannot define multiple parsers of the same type with different parameters on one column. +- Parser attributes (`multilingual`, `ngram`) and filter attributes (`exact`, `path_hierarchy`) cannot coexist on the same column. A column is either a scored column or a filter column. +- Syntax sugar mode does not support filter columns. To define filter columns, use column-property mode. +- When a column declares more than one parser attribute, a query uses the parser named by `WITH PARSER`, or the first parser attribute in the index definition when the clause is absent. A query that expects the other parser without naming it returns the results of the parser it landed on, with no warning. See [Select a parser for a scored column](/ai/reference/full-text-search-functions-tidb.md#select-a-parser-for-a-scored-column). +- A TiFlash replica and the full-text indexes on it are built asynchronously. A successful `CREATE TABLE` or `ALTER TABLE` statement does not mean the index is queryable, and a query that runs before the index is ready returns no rows rather than an error. Before you rely on the result, confirm that the replica is available and run a query whose match you know: + + ```sql + SELECT TABLE_NAME, REPLICA_COUNT, AVAILABLE + FROM INFORMATION_SCHEMA.TIFLASH_REPLICA + WHERE TABLE_SCHEMA = 'your_database' AND TABLE_NAME = 'your_table'; + + SELECT COUNT(*) FROM your_table WHERE FTS_MATCH_WORD('known_term', content_text); + ``` + + `AVAILABLE = 0` means the replica is still being built. When a query returns no rows, rule out the causes in [Query limitations](#query-limitations) before you conclude that data is missing. + +## Filter pushdown limitations + +- The `exact` attribute supports equality matching (`=` and `IN`) in the index scan. Range predicates (`<`, `>`, `BETWEEN`, and similar) on `exact` columns are not pushed down into the index scan. They are evaluated as residual predicates after row lookup, so query results remain correct but the filtering happens outside the index. +- `LIKE` conditions on `exact` columns are not pushed down into the index scan and are evaluated as residual predicates. `LIKE` prefix matching is pushed down only on columns with the `path_hierarchy` attribute. +- For `path_hierarchy` columns, a pushed-down prefix must align with a delimiter boundary. For example, with the default delimiter `/`, `path LIKE '/src/%'` is pushed down, but `path LIKE '/src/par%'` is not, because the prefix ends inside a directory name. Such conditions are evaluated as residual predicates after row lookup. +- Filter conditions that cannot match any filter column of the selected index are evaluated as residual predicates after row lookup. + +## Query limitations + +- In the `WHERE` clause, multiple `FTS_MATCH_WORD()` calls can be combined only with `OR`. Combining them with `AND` at the top level returns `ERROR 1221 (HY000): Currently 'FTS_MATCH_WORD()' must be used alone`, even when the calls use different words or different columns. To express AND or NOT semantics, use `INTERSECT` or `EXCEPT`. See [Multi-word query semantics](/ai/reference/full-text-search-functions-tidb.md#multi-word-query-semantics). + +- `ORDER BY` with `FTS_MATCH_WORD()` requires a `LIMIT` clause, and is supported only when the `WHERE` clause contains a single `FTS_MATCH_WORD()` call: + + ```sql + -- Not supported: ORDER BY a match function without a LIMIT clause + SELECT * FROM t + WHERE FTS_MATCH_WORD('database', content_text) + ORDER BY FTS_MATCH_WORD('database', content_text) DESC; + + -- Not supported: multiple match functions in WHERE, ordered by one of them + SELECT * FROM t + WHERE FTS_MATCH_WORD('database', content_text) + OR FTS_MATCH_WORD('vector', content_text) + ORDER BY FTS_MATCH_WORD('database', content_text) DESC + LIMIT 10; + ``` + + To rank the complete result set in one statement, specify a large `LIMIT` value. Ordering by a regular column requires no `LIMIT`. + +- `FTS_MATCH_WORD()` cannot appear in `GROUP BY` or `HAVING` clauses. +- `FTS_MATCH_WORD()` cannot be nested inside another function or expression. Comparing its score in the same clause, as in `WHERE FTS_MATCH_WORD('database', content_text) > 0.5`, returns `ERROR 1221 (HY000): Currently 'FTS_MATCH_WORD()' must be used alone`. To filter by score, compute it in a derived table and filter in the outer query: + + ```sql + SELECT * FROM ( + SELECT id, FTS_MATCH_WORD('database', content_text) AS score + FROM t + WHERE FTS_MATCH_WORD('database', content_text) + ORDER BY score DESC + LIMIT 100 + ) s + WHERE s.score > 0.5; + ``` + +- When `FTS_MATCH_WORD()` appears in the `SELECT` list, the `WHERE` clause must contain the same call, including any `WITH PARSER` clause, and `ORDER BY` must either repeat that call or reference its alias: + + ```sql + SELECT id, FTS_MATCH_WORD('database', content_text) AS score + FROM t + WHERE FTS_MATCH_WORD('database', content_text) + ORDER BY score DESC + LIMIT 10; + ``` + + Otherwise TiDB returns `ERROR 1221 (HY000): 'FTS_MATCH_WORD()' in SELECT requires a matching 'FTS_MATCH_WORD()' in WHERE.` + +- Applying `NOT` directly to `FTS_MATCH_WORD()` in the `WHERE` clause returns `ERROR 1221 (HY000): scored pure-negative FTS match expression is not supported`. To exclude matching rows, use `EXCEPT`, or place `NOT` inside an `OR` branch alongside a positive term. +- Calling `FTS_MATCH_WORD()` on a column that carries the `exact` attribute returns `ERROR 1221 (HY000): FTS_MATCH_WORD does not support fields using the EXACT parser; use = or IN predicates instead`. Filter columns take `=` and `IN` predicates. A `WITH PARSER` clause on such a column is rejected for the same reason. +- The `WITH PARSER` clause in `FTS_MATCH_WORD()` takes a parser name only. Parameters such as `WITH PARSER ngram(min_gram=5)` are not accepted, because gram sizes belong to the index definition. Naming a parser that the column does not have returns an error rather than falling back to another parser. +- In a multi-column `FTS_MATCH_WORD()` call, the parsers named for the scored columns must all exist in one full-text index. When no single index satisfies them, TiDB returns an error instead of scanning one index per column and merging the scores outside the index. +- A query term shorter than the `min_gram` of an NGRAM index matches no rows, because the index holds no shorter tokens. Wildcards such as `%` have no special meaning inside `FTS_MATCH_WORD()`; such a query returns no rows instead of an error. +- `EXCEPT ALL` and `INTERSECT ALL` are not supported. Use `EXCEPT` and `INTERSECT`, which eliminate duplicate rows: + + ``` + ERROR 1105 (HY000): TiDB do not support except all + ``` + +- The default `mysql` client strips optimizer hints such as `USE_INDEX`, which silently changes the index and therefore the parser a query uses. Run the client with `-c` or `--comments` when you test hinted full-text queries, and check `SHOW WARNINGS` or the `EXPLAIN` output to confirm that a hint takes effect. A `WITH PARSER` clause is part of the function argument list and is not stripped. + + + +- Exact phrase matching, where all query tokens must appear consecutively and in the specified order, is not supported yet. +- Only `INNER JOIN` is supported with full-text search. Outer joins (`LEFT`, `RIGHT`, and `FULL`) and comma-separated table lists, which form an implicit `CROSS JOIN`, are not supported yet. +- In compound statements (`UNION`, `UNION ALL`, `EXCEPT`, and `INTERSECT`), each branch matches its full-text index independently. Branches do not share a single index scan, and the outer `ORDER BY` and `LIMIT` are not pushed into the full-text scans. +- A query that uses `FTS_MATCH_WORD()` must match a full-text index that covers the queried columns. When no such index exists, or when `IGNORE_INDEX` excludes all of them, TiDB returns an error instead of falling back to a table scan: + + ``` + ERROR 1221 (HY000): full text search can only be used with a matching current TiFlash full-text index path + ``` + + When a `USE_INDEX` hint names an index that does not cover a column used by the query, TiDB reports the index and the column in the error, for example: `ERROR 1221 (HY000): full-text search index idx_fts_ng does not cover column test.docs.ext`. + +## Observability limitations + +- Full-text indexes do not report usage or size statistics in this version. TiDB does not record full-text index accesses in `INFORMATION_SCHEMA.TIDB_INDEX_USAGE`, provides no full-text statistics tables, and exposes no full-text query time metrics. Use `EXPLAIN` together with the slow query log to investigate a query. + +## DML limitations + +- Full-text search is supported in query statements. To change the rows that a full-text search matches, first retrieve the IDs, then run the DML statement with that list: + + ```sql + -- Step 1. Retrieve the matching IDs + SELECT id FROM t WHERE FTS_MATCH_WORD('obsolete', content_text); + + -- Step 2. Run the DML statement with the IDs from the previous result + DELETE FROM t WHERE id IN (5, 8, 11); + ``` + +## DDL limitations + +See [DDL restrictions](/ai/reference/full-text-search-index.md#ddl-restrictions) in [Full-Text Search Index](/ai/reference/full-text-search-index.md). + +## Feedback + +We value your feedback and are always here to help: + +- Ask the community on [Discord](https://discord.gg/DQZ2dy3cuc?utm_source=doc) or [Slack](https://slack.tidb.io/invite?team=tidb-community&channel=everyone&ref=pingcap-docs). +- [Submit a support ticket for TiDB Cloud](https://tidb.support.pingcap.com/servicedesk/customer/portals)