From 179a349ddb741f992b1d51f38fddcd4c8310640d Mon Sep 17 00:00:00 2001 From: zhaoshangzi Date: Tue, 24 Nov 2026 14:45:23 +0800 Subject: [PATCH 1/5] c1 --- TOC-ai.md | 11 +- ai/guides/fulltext-search-with-pytidb.md | 4 + .../vector-search-full-text-search-sql.md | 152 ++++++--- .../full-text-search-functions-tidb.md | 218 ++++++++++++ ai/reference/full-text-search-index.md | 318 ++++++++++++++++++ ai/reference/full-text-search-limitations.md | 53 +++ 6 files changed, 709 insertions(+), 47 deletions(-) create mode 100644 ai/reference/full-text-search-functions-tidb.md create mode 100644 ai/reference/full-text-search-index.md create mode 100644 ai/reference/full-text-search-limitations.md 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..07fe1d602032f 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 **available only on {{{ .starter }}}** in [select regions](/ai/reference/full-text-search-index.md#prerequisites). + ## 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..d061bb954d8d8 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. +- **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`. + - **Fully compatible with SQL**: all SQL features, such as pre-filtering, post-filtering, grouping, and joining, can be used with full-text search. > **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. @@ -204,9 +196,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 +213,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. Use the `USE_INDEX` hint to select an index at query time, or let the optimizer choose automatically. For parameters and query semantics, see [The NGRAM parser](/ai/reference/full-text-search-index.md#the-ngram-parser) 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 +274,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,6 +297,37 @@ 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. @@ -316,6 +377,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..40dac2d2eb623 --- /dev/null +++ b/ai/reference/full-text-search-functions-tidb.md @@ -0,0 +1,218 @@ +--- +title: TiDB Full-Text Search Functions +summary: Learn the full-text search functions in TiDB, including query syntax, multi-column search, parser selection, and index selection hints. +--- + +# TiDB Full-Text Search Functions + +This document describes the `FTS_MATCH_WORD()` function for full-text search in TiDB, including multi-column search, query semantics with different parsers, parser selection, and index selection hints. + +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 **available only on {{{ .starter }}}** in [select regions](/ai/reference/full-text-search-index.md#prerequisites). + +## 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' [WITH PARSER parser_name], col [, col...]) +``` + +| Parameter | Description | +| :-- | :-- | +| `query` | The search text. It is tokenized according to the parser rules of the matched index. | +| `WITH PARSER parser_name` | Optional. Explicitly selects which parser to use when the scored column has multiple parsers. Only a parser name is accepted, such as `multilingual` or `ngram`. Parser parameters are not allowed. See [Select a parser explicitly](#select-a-parser-explicitly). | +| `col [, col...]` | One or more scored columns. The columns can be a subset of the scored columns of a full-text index. | + +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; +``` + +To require all columns to match (**AND** semantics), combine multiple `FTS_MATCH_WORD()` calls with `AND` in the `WHERE` clause: + +```sql +SELECT * FROM t +WHERE FTS_MATCH_WORD('database', content_text) + AND FTS_MATCH_WORD('database', description); +``` + +In a multi-column query, each column is tokenized by the parser defined for that column in the index, 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); +``` + +To require multiple words to match (**AND** semantics), combine multiple `FTS_MATCH_WORD()` calls with `AND`. The optimizer merges the conditions into a single index scan: + +```sql +SELECT * FROM t +WHERE FTS_MATCH_WORD('database', content_text) + AND FTS_MATCH_WORD('vector', content_text); +``` + +Similarly, multiple calls combined with `OR` are merged into one scan with OR semantics: + +```sql +SELECT * FROM t +WHERE FTS_MATCH_WORD('database', content_text) + OR 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 explicitly + +When a scored column has multiple parsers (for example, `content_text WITH (multilingual, ngram(...))`), use the `WITH PARSER` clause inside the function to select one explicitly. Only a parser name is accepted. Parser parameters such as `WITH PARSER ngram(min_gram=5)` are not allowed and return an error. + +```sql +-- Use the ngram parser explicitly +SELECT * FROM t +WHERE FTS_MATCH_WORD('handle' WITH PARSER ngram, content_text); + +-- Without WITH PARSER, the first compatible parser in the index definition is used +SELECT * FROM t +WHERE FTS_MATCH_WORD('database', content_text); +``` + +Parser selection rules: + +| Scenario | Behavior | +| :-- | :-- | +| `WITH PARSER parser_name` is specified, and the column has an index with that parser | The specified parser is used. | +| `WITH PARSER parser_name` is specified, but the column has no index with that parser | An error is returned: `ERROR: Parser 'xxx' not found for column 'yyy' in fts_match_word`. TiDB does not silently fall back to another parser. | +| `WITH PARSER` is omitted, and the column has one compatible parser | That parser is used. | +| `WITH PARSER` is omitted, and the column has multiple compatible parsers | The first compatible parser in the index definition is used. If `USE_INDEX` is also specified, the parser of the specified index is used. See [Choose a full-text index at query time](#choose-a-full-text-index-at-query-time). | + +> **Note:** +> +> Parser selection is part of query semantics, not performance tuning. Different parsers return different results. For this reason, you select a parser with `WITH PARSER` inside the function, not with an optimizer hint. If the specified parser does not exist, TiDB reports an error instead of falling back silently, so that results always match the parser you requested. + +## 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 | +| :-- | :-- | +| Intended use case | Select among multiple indexes that use the same parser. This is a pure execution-path choice. | +| Conflicts with `WITH PARSER` in the function (the specified index does not contain that parser) | `USE_INDEX` is ignored. The parser in `WITH PARSER` takes precedence, and TiDB selects another index that contains that parser. | +| `WITH PARSER` is not specified | TiDB follows `USE_INDEX` and uses the specified index and its parser. | +| The specified index does not exist | The hint is silently ignored, and the optimizer selects an index automatically. | + +### IGNORE_INDEX: exclude an index + +```sql +SELECT /*+ IGNORE_INDEX(t, idx_fts_ngram) */ * +FROM t WHERE FTS_MATCH_WORD('handle', content_text); +``` + +### 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. | + +The optimizer also compares the full-text index scan against a full table scan or a regular index scan, and chooses the path with the lowest estimated cost. + +## 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; + ``` + +- `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..4298fccabde77 --- /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). + +## Prerequisites + +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)` + +## 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:** +> +> - In syntax sugar mode, specifying an index name is optional for the `MULTILINGUAL` parser. If you use the `NGRAM` parser or column-property mode, you must specify an index name explicitly. 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, ngram(min_gram=3, max_gram=3)), + 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, `content_text WITH (multilingual, ngram(...))` builds two tokenizer structures for the same column, and `path WITH (exact, path_hierarchy)` makes the column support both equality filters and path prefix filters. +- 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 `col LIKE '/src/%'` and `col UNDER '/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. + +```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, you can select the index with the `USE_INDEX` or `IGNORE_INDEX` optimizer hint, or let the optimizer choose automatically. See [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`. +- `INFORMATION_SCHEMA.TIDB_INDEX_USAGE`: reports access statistics for full-text indexes. + +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..95c6835070529 --- /dev/null +++ b/ai/reference/full-text-search-limitations.md @@ -0,0 +1,53 @@ +--- +title: Full-Text Search Limitations +summary: Learn the limitations of full-text search in TiDB, including index definition, filter pushdown, query syntax, and DDL restrictions. +--- + +# Full-Text Search Limitations + +This document describes the known limitations of full-text search in TiDB. + +> **Note:** +> +> 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 [select regions](/ai/reference/full-text-search-index.md#prerequisites). + +## 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. + +## 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 + +- `ORDER BY` with a match function is only supported when the `WHERE` clause contains a single match function call. When the `WHERE` clause contains multiple match functions (for example, multi-word AND or OR combinations), ordering by a match function in the same query is not supported. + + ```sql + -- Not supported: multiple match functions in WHERE and ORDER BY on a match function + SELECT * FROM t + WHERE FTS_MATCH_WORD('database', col) AND FTS_MATCH_WORD('vector', col) + ORDER BY FTS_MATCH_WORD('database', col) DESC; + ``` + +- `FTS_MATCH_WORD()` cannot appear in `GROUP BY` or `HAVING` clauses. +- 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`) 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. + +## 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) From d5a96767b0b3b51b3d1577bc352d1b671e702c71 Mon Sep 17 00:00:00 2001 From: zhaoshangzi Date: Tue, 24 Nov 2026 15:34:00 +0800 Subject: [PATCH 2/5] c2 --- .../vector-search-full-text-search-sql.md | 10 +- .../full-text-search-functions-tidb.md | 109 ++++++++++++------ ai/reference/full-text-search-index.md | 10 +- ai/reference/full-text-search-limitations.md | 21 +++- 4 files changed, 105 insertions(+), 45 deletions(-) diff --git a/ai/guides/vector-search-full-text-search-sql.md b/ai/guides/vector-search-full-text-search-sql.md index d061bb954d8d8..e054d88e833b8 100644 --- a/ai/guides/vector-search-full-text-search-sql.md +++ b/ai/guides/vector-search-full-text-search-sql.md @@ -22,7 +22,7 @@ The full-text search feature in TiDB provides the following capabilities: - **Substring matching**: with the NGRAM parser, queries can match prefixes and substrings, such as matching `panic_handler` when searching for `panic`. -- **Fully compatible with SQL**: all SQL features, such as pre-filtering, post-filtering, grouping, and joining, can be used with full-text search. +- **SQL-native**: you can combine full-text search with filter conditions, aggregation, joins, and subqueries in ordinary SQL statements, without maintaining a separate search engine. > **Tip:** > @@ -181,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 @@ -236,7 +240,7 @@ FROM code_files 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. Use the `USE_INDEX` hint to select an index at query time, or let the optimizer choose automatically. For parameters and query semantics, see [The NGRAM parser](/ai/reference/full-text-search-index.md#the-ngram-parser) 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). +A table can have multiple full-text indexes, and the same column can participate in several of them with different parsers. Specify the index with the `USE_INDEX` hint, because the hinted index determines the parser and therefore the result set. Without a hint, 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) 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 @@ -359,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 diff --git a/ai/reference/full-text-search-functions-tidb.md b/ai/reference/full-text-search-functions-tidb.md index 40dac2d2eb623..2d4e2a542d590 100644 --- a/ai/reference/full-text-search-functions-tidb.md +++ b/ai/reference/full-text-search-functions-tidb.md @@ -1,11 +1,11 @@ --- title: TiDB Full-Text Search Functions -summary: Learn the full-text search functions in TiDB, including query syntax, multi-column search, parser selection, and index selection hints. +summary: Learn how to search text with the FTS_MATCH_WORD() function, including multi-column queries and full-text index selection. --- # TiDB Full-Text Search Functions -This document describes the `FTS_MATCH_WORD()` function for full-text search in TiDB, including multi-column search, query semantics with different parsers, parser selection, and index selection hints. +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 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). @@ -18,15 +18,16 @@ For how to create the full-text indexes that these functions use, see [Full-Text `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' [WITH PARSER parser_name], col [, col...]) +FTS_MATCH_WORD('query', col [, col...]) ``` | Parameter | Description | | :-- | :-- | -| `query` | The search text. It is tokenized according to the parser rules of the matched index. | -| `WITH PARSER parser_name` | Optional. Explicitly selects which parser to use when the scored column has multiple parsers. Only a parser name is accepted, such as `multilingual` or `ngram`. Parser parameters are not allowed. See [Select a parser explicitly](#select-a-parser-explicitly). | +| `query` | The search text. It is tokenized according to the parser of the full-text index that the query runs on. | | `col [, col...]` | One or more scored columns. The columns can be a subset of the scored columns of a full-text index. | +To search the same column with different parsers, create one full-text index per parser and select the index with the `USE_INDEX` hint. 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 @@ -51,12 +52,12 @@ ORDER BY FTS_MATCH_WORD('database', content_text, description) DESC LIMIT 10; ``` -To require all columns to match (**AND** semantics), combine multiple `FTS_MATCH_WORD()` calls with `AND` in the `WHERE` clause: +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 * FROM t -WHERE FTS_MATCH_WORD('database', content_text) - AND FTS_MATCH_WORD('database', description); +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 defined for that column in the index, 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. @@ -71,20 +72,43 @@ When the query string contains multiple words, it is tokenized according to the SELECT * FROM users WHERE FTS_MATCH_WORD('Alice Smith', name); ``` -To require multiple words to match (**AND** semantics), combine multiple `FTS_MATCH_WORD()` calls with `AND`. The optimizer merges the conditions into a single index scan: +Multiple calls combined with `OR` are merged into one index scan: ```sql SELECT * FROM t WHERE FTS_MATCH_WORD('database', content_text) - AND FTS_MATCH_WORD('vector', 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. ``` -Similarly, multiple calls combined with `OR` are merged into one scan with OR semantics: +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 FTS_MATCH_WORD('database', content_text) - OR FTS_MATCH_WORD('vector', content_text); +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 @@ -116,32 +140,33 @@ If the query string contains repeated terms, the term frequency of that term is 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 explicitly +## Select a parser for a scored column -When a scored column has multiple parsers (for example, `content_text WITH (multilingual, ngram(...))`), use the `WITH PARSER` clause inside the function to select one explicitly. Only a parser name is accepted. Parser parameters such as `WITH PARSER ngram(min_gram=5)` are not allowed and return an error. +A query is tokenized by the parser of the full-text index it runs on. To search one column with more than one parser, create a separate full-text index for each parser, then select the index with the `USE_INDEX` hint: ```sql --- Use the ngram parser explicitly -SELECT * FROM t -WHERE FTS_MATCH_WORD('handle' WITH PARSER ngram, content_text); +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); +``` --- Without WITH PARSER, the first compatible parser in the index definition is used -SELECT * FROM t +```sql +-- Substring matching: the NGRAM index matches 'hand' inside 'HandleRequest' +SELECT /*+ USE_INDEX(t, idx_fts_ngram) */ * FROM t +WHERE FTS_MATCH_WORD('hand', content_text); + +-- Complete token matching: the MULTILINGUAL index matches whole tokens only +SELECT /*+ USE_INDEX(t, idx_fts_ml) */ * FROM t WHERE FTS_MATCH_WORD('database', content_text); ``` -Parser selection rules: +The `WITH PARSER` clause is accepted only in an index definition, as part of `FULLTEXT INDEX (col) WITH PARSER parser_name`. It is not supported inside `FTS_MATCH_WORD()`, and writing it there returns a syntax error. -| Scenario | Behavior | -| :-- | :-- | -| `WITH PARSER parser_name` is specified, and the column has an index with that parser | The specified parser is used. | -| `WITH PARSER parser_name` is specified, but the column has no index with that parser | An error is returned: `ERROR: Parser 'xxx' not found for column 'yyy' in fts_match_word`. TiDB does not silently fall back to another parser. | -| `WITH PARSER` is omitted, and the column has one compatible parser | That parser is used. | -| `WITH PARSER` is omitted, and the column has multiple compatible parsers | The first compatible parser in the index definition is used. If `USE_INDEX` is also specified, the parser of the specified index is used. See [Choose a full-text index at query time](#choose-a-full-text-index-at-query-time). | +Declaring two parser attributes on one column of the same index, such as `content_text WITH (multilingual, ngram(min_gram=3, max_gram=3))`, succeeds but is not usable: the query can run on only one of the parsers, and you have no way to select the other one. To search a column with both parsers, use separate indexes. > **Note:** > -> Parser selection is part of query semantics, not performance tuning. Different parsers return different results. For this reason, you select a parser with `WITH PARSER` inside the function, not with an optimizer hint. If the specified parser does not exist, TiDB reports an error instead of falling back silently, so that results always match the parser you requested. +> Selecting the index selects the parser, which changes the result set. This makes parser selection part of query semantics, not performance tuning. Automatic index selection does not compare parsers, so when a scored column has indexes with different parsers, always specify the index with `USE_INDEX`. See [Automatic index selection](#automatic-index-selection). ## Choose a full-text index at query time @@ -163,10 +188,10 @@ FROM t WHERE FTS_MATCH_WORD('database', content_text); | Scenario | Behavior | | :-- | :-- | -| Intended use case | Select among multiple indexes that use the same parser. This is a pure execution-path choice. | -| Conflicts with `WITH PARSER` in the function (the specified index does not contain that parser) | `USE_INDEX` is ignored. The parser in `WITH PARSER` takes precedence, and TiDB selects another index that contains that parser. | -| `WITH PARSER` is not specified | TiDB follows `USE_INDEX` and uses the specified index and its parser. | -| The specified index does not exist | The hint is silently ignored, and the optimizer selects an index automatically. | +| The indexes differ only in parser | The hint selects the parser, so the result set changes. This is the supported way to route a query between parsers. | +| The indexes use the same parser | A pure execution-path choice. The result set is unchanged. | +| The specified index does not exist | The hint is silently ignored, and the optimizer selects an index automatically. This follows the convention for optimizer hints. | +| The specified index does not cover a column that the query uses | TiDB returns an error, for example: `ERROR 1221 (HY000): full-text search index idx_fts_ngram does not cover column test.docs.ext`. | ### IGNORE_INDEX: exclude an index @@ -175,6 +200,12 @@ 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: @@ -185,7 +216,9 @@ Without hints, the optimizer selects a full-text index by the following prioriti | 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. | -The optimizer also compares the full-text index scan against a full table scan or a regular index scan, and chooses the path with the lowest estimated cost. +These priorities do not compare parsers. When one column has full-text indexes with different parsers, the automatically selected index determines the matching behavior of the query without any warning, so specify 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 @@ -199,6 +232,14 @@ The optimizer also compares the full-text index scan against a full table scan o 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 diff --git a/ai/reference/full-text-search-index.md b/ai/reference/full-text-search-index.md index 4298fccabde77..668e439dfb726 100644 --- a/ai/reference/full-text-search-index.md +++ b/ai/reference/full-text-search-index.md @@ -59,7 +59,8 @@ In column-property mode, each column declares one or more attributes in a `WITH ```sql ALTER TABLE t ADD FULLTEXT INDEX idx_fts ( - content_text WITH (multilingual, ngram(min_gram=3, max_gram=3)), + content_text WITH (multilingual), + description WITH (multilingual), path WITH (exact, path_hierarchy), name WITH (exact), ext WITH (exact) @@ -73,7 +74,8 @@ Attributes fall into two categories: Rules for column attributes: -- A column can have multiple attributes, separated by commas inside `WITH (...)`. For example, `content_text WITH (multilingual, ngram(...))` builds two tokenizer structures for the same column, and `path WITH (exact, path_hierarchy)` makes the column support both equality filters and path prefix filters. +- 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. +- Assign one parser attribute to each scored column. Declaring two parsers on one column, such as `content_text WITH (multilingual, ngram(...))`, creates the index without an error, but a query can run on only one of them and there is no way to select the other, so a query that expects the unused parser returns no rows. To search one column with several parsers, create a separate full-text index for each parser. See [Multiple indexes on one table](#multiple-indexes-on-one-table). - 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). @@ -86,7 +88,7 @@ Rules for column attributes: | `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 `col LIKE '/src/%'` and `col UNDER '/src/'`. The prefix must align with a delimiter boundary. +| `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`: @@ -175,7 +177,7 @@ ALTER TABLE t ADD FULLTEXT INDEX idx_fts_ng (content_text) WITH PARSER NGRAM(min_gram=3, max_gram=3); ``` -At query time, you can select the index with the `USE_INDEX` or `IGNORE_INDEX` optimizer hint, or let the optimizer choose automatically. See [Choose a full-text index at query time](/ai/reference/full-text-search-functions-tidb.md#choose-a-full-text-index-at-query-time). +At query time, select the index with the `USE_INDEX` or `IGNORE_INDEX` optimizer hint. When indexes on the same column use different parsers, specify the index explicitly: automatic selection does not compare parsers, so the matching behavior of the query is not what you intend. See [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 diff --git a/ai/reference/full-text-search-limitations.md b/ai/reference/full-text-search-limitations.md index 95c6835070529..97a1f341fb168 100644 --- a/ai/reference/full-text-search-limitations.md +++ b/ai/reference/full-text-search-limitations.md @@ -17,6 +17,7 @@ This document describes the known limitations of full-text search in TiDB. - 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. +- Declaring more than one parser attribute on a single column of the same index, such as `content_text WITH (multilingual, ngram(...))`, succeeds but does not give you both matching behaviors: a query runs on one of the parsers and cannot select the other. Create one full-text index per parser instead. ## Filter pushdown limitations @@ -27,19 +28,31 @@ This document describes the known limitations of full-text search in TiDB. ## Query limitations -- `ORDER BY` with a match function is only supported when the `WHERE` clause contains a single match function call. When the `WHERE` clause contains multiple match functions (for example, multi-word AND or OR combinations), ordering by a match function in the same query is not supported. +- 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: multiple match functions in WHERE and ORDER BY on a match function + -- 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', col) AND FTS_MATCH_WORD('vector', col) - ORDER BY FTS_MATCH_WORD('database', col) DESC; + 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. - 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`) 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. ## DDL limitations From d50dcaae79f4826a89ffe1395b572ce0f3e351c1 Mon Sep 17 00:00:00 2001 From: zhaoshangzi Date: Tue, 24 Nov 2026 16:02:40 +0800 Subject: [PATCH 3/5] c3 --- .../vector-search-full-text-search-sql.md | 4 +- .../full-text-search-functions-tidb.md | 6 +- ai/reference/full-text-search-index.md | 5 +- ai/reference/full-text-search-limitations.md | 74 ++++++++++++++++++- 4 files changed, 79 insertions(+), 10 deletions(-) diff --git a/ai/guides/vector-search-full-text-search-sql.md b/ai/guides/vector-search-full-text-search-sql.md index e054d88e833b8..b9e0aacf385a6 100644 --- a/ai/guides/vector-search-full-text-search-sql.md +++ b/ai/guides/vector-search-full-text-search-sql.md @@ -22,7 +22,7 @@ The full-text search feature in TiDB provides the following capabilities: - **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, joins, and subqueries in ordinary SQL statements, without maintaining a separate search engine. +- **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:** > @@ -334,7 +334,7 @@ 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: diff --git a/ai/reference/full-text-search-functions-tidb.md b/ai/reference/full-text-search-functions-tidb.md index 2d4e2a542d590..444d4ea8ae288 100644 --- a/ai/reference/full-text-search-functions-tidb.md +++ b/ai/reference/full-text-search-functions-tidb.md @@ -162,7 +162,7 @@ WHERE FTS_MATCH_WORD('database', content_text); The `WITH PARSER` clause is accepted only in an index definition, as part of `FULLTEXT INDEX (col) WITH PARSER parser_name`. It is not supported inside `FTS_MATCH_WORD()`, and writing it there returns a syntax error. -Declaring two parser attributes on one column of the same index, such as `content_text WITH (multilingual, ngram(min_gram=3, max_gram=3))`, succeeds but is not usable: the query can run on only one of the parsers, and you have no way to select the other one. To search a column with both parsers, use separate indexes. +An index provides only one parser per column, so separate indexes are the only way to search one column with both complete-token and substring matching. For the underlying restriction, see [Index limitations](/ai/reference/full-text-search-limitations.md#index-limitations). > **Note:** > @@ -190,8 +190,8 @@ FROM t WHERE FTS_MATCH_WORD('database', content_text); | :-- | :-- | | The indexes differ only in parser | The hint selects the parser, so the result set changes. This is the supported way to route a query between parsers. | | The indexes use the same parser | A pure execution-path choice. The result set is unchanged. | -| The specified index does not exist | The hint is silently ignored, and the optimizer selects an index automatically. This follows the convention for optimizer hints. | -| The specified index does not cover a column that the query uses | TiDB returns an error, for example: `ERROR 1221 (HY000): full-text search index idx_fts_ngram does not cover column test.docs.ext`. | +| 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 diff --git a/ai/reference/full-text-search-index.md b/ai/reference/full-text-search-index.md index 668e439dfb726..218feaeb7248e 100644 --- a/ai/reference/full-text-search-index.md +++ b/ai/reference/full-text-search-index.md @@ -50,7 +50,7 @@ Syntax sugar mode is equivalent to column-property mode with a single parser att > **Note:** > -> - In syntax sugar mode, specifying an index name is optional for the `MULTILINGUAL` parser. If you use the `NGRAM` parser or column-property mode, you must specify an index name explicitly. See [Index naming](#index-naming). +> - 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 @@ -221,7 +221,8 @@ You can also query `INFORMATION_SCHEMA`: - `INFORMATION_SCHEMA.STATISTICS`: `INDEX_TYPE` returns `FULLTEXT`. - `INFORMATION_SCHEMA.TIDB_INDEXES`: `index_type` returns `FULLTEXT`. -- `INFORMATION_SCHEMA.TIDB_INDEX_USAGE`: reports access statistics for full-text indexes. + +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: diff --git a/ai/reference/full-text-search-limitations.md b/ai/reference/full-text-search-limitations.md index 97a1f341fb168..8697cca06cbf8 100644 --- a/ai/reference/full-text-search-limitations.md +++ b/ai/reference/full-text-search-limitations.md @@ -1,6 +1,6 @@ --- title: Full-Text Search Limitations -summary: Learn the limitations of full-text search in TiDB, including index definition, filter pushdown, query syntax, and DDL restrictions. +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 @@ -18,6 +18,17 @@ This document describes the known limitations of full-text search in TiDB. - 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. - Declaring more than one parser attribute on a single column of the same index, such as `content_text WITH (multilingual, ngram(...))`, succeeds but does not give you both matching behaviors: a query runs on one of the parsers and cannot select the other. Create one full-text index per parser instead. +- 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 @@ -49,10 +60,67 @@ This document describes the known limitations of full-text search in TiDB. 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, 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 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. - 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`) are 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. +- 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 From 2e0f8cb662a269e17ddc91167ceaffa0adb1a7c4 Mon Sep 17 00:00:00 2001 From: Lilian Lee Date: Wed, 25 Nov 2026 11:56:33 +0800 Subject: [PATCH 4/5] Apply suggestions from code review Co-authored-by: Grace Cai --- ai/guides/fulltext-search-with-pytidb.md | 2 +- ai/reference/full-text-search-functions-tidb.md | 2 +- ai/reference/full-text-search-index.md | 9 +++------ ai/reference/full-text-search-limitations.md | 2 +- 4 files changed, 6 insertions(+), 9 deletions(-) diff --git a/ai/guides/fulltext-search-with-pytidb.md b/ai/guides/fulltext-search-with-pytidb.md index 07fe1d602032f..881d3f3c61f5b 100644 --- a/ai/guides/fulltext-search-with-pytidb.md +++ b/ai/guides/fulltext-search-with-pytidb.md @@ -21,7 +21,7 @@ Before you begin, ensure you have the following: > **Note:** > - > Currently, full-text search is **available only on {{{ .starter }}}** in [select regions](/ai/reference/full-text-search-index.md#prerequisites). + > Currently, full-text search is in public preview and **available only on {{{ .starter }}}**. ## How to run diff --git a/ai/reference/full-text-search-functions-tidb.md b/ai/reference/full-text-search-functions-tidb.md index 444d4ea8ae288..37862d8750b6e 100644 --- a/ai/reference/full-text-search-functions-tidb.md +++ b/ai/reference/full-text-search-functions-tidb.md @@ -11,7 +11,7 @@ For how to create the full-text indexes that these functions use, see [Full-Text > **Note:** > -> Currently, full-text search is **available only on {{{ .starter }}}** in [select regions](/ai/reference/full-text-search-index.md#prerequisites). +> Currently, full-text search is in public preview and **available only on {{{ .starter }}}**. ## FTS_MATCH_WORD() diff --git a/ai/reference/full-text-search-index.md b/ai/reference/full-text-search-index.md index 218feaeb7248e..feeebb593744f 100644 --- a/ai/reference/full-text-search-index.md +++ b/ai/reference/full-text-search-index.md @@ -9,12 +9,9 @@ This document describes how to create and manage full-text indexes in TiDB, incl To run full-text queries against a full-text index, see [Full-Text Search Functions](/ai/reference/full-text-search-functions-tidb.md). -## Prerequisites - -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)` - +> **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: diff --git a/ai/reference/full-text-search-limitations.md b/ai/reference/full-text-search-limitations.md index 8697cca06cbf8..5bd03321a1c77 100644 --- a/ai/reference/full-text-search-limitations.md +++ b/ai/reference/full-text-search-limitations.md @@ -9,7 +9,7 @@ This document describes the known limitations of full-text search in TiDB. > **Note:** > -> 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 [select regions](/ai/reference/full-text-search-index.md#prerequisites). +> Currently, full-text search is in public preview and **available only on {{{ .starter }}}**. ## Index limitations From 9bd21f2bf3e851980331beb48fb38f36a869c3d8 Mon Sep 17 00:00:00 2001 From: zhaoshangzi Date: Sun, 6 Dec 2026 16:38:50 +0800 Subject: [PATCH 5/5] c4 --- .../vector-search-full-text-search-sql.md | 2 +- .../full-text-search-functions-tidb.md | 74 ++++++++++++++----- ai/reference/full-text-search-index.md | 6 +- ai/reference/full-text-search-limitations.md | 13 +++- 4 files changed, 70 insertions(+), 25 deletions(-) diff --git a/ai/guides/vector-search-full-text-search-sql.md b/ai/guides/vector-search-full-text-search-sql.md index b9e0aacf385a6..ffde031b438d7 100644 --- a/ai/guides/vector-search-full-text-search-sql.md +++ b/ai/guides/vector-search-full-text-search-sql.md @@ -240,7 +240,7 @@ FROM code_files 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. Specify the index with the `USE_INDEX` hint, because the hinted index determines the parser and therefore the result set. Without a hint, 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) 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). +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 diff --git a/ai/reference/full-text-search-functions-tidb.md b/ai/reference/full-text-search-functions-tidb.md index 37862d8750b6e..49c1b379c4f0e 100644 --- a/ai/reference/full-text-search-functions-tidb.md +++ b/ai/reference/full-text-search-functions-tidb.md @@ -1,11 +1,11 @@ --- title: TiDB Full-Text Search Functions -summary: Learn how to search text with the FTS_MATCH_WORD() function, including multi-column queries and full-text index selection. +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 full-text index that a query runs on. +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). @@ -18,15 +18,15 @@ For how to create the full-text indexes that these functions use, see [Full-Text `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 [, col...]) +FTS_MATCH_WORD('query', col [WITH PARSER parser_name] [, col [WITH PARSER parser_name]...]) ``` | Parameter | Description | | :-- | :-- | -| `query` | The search text. It is tokenized according to the parser of the full-text index that the query runs on. | -| `col [, col...]` | One or more scored columns. The columns can be a subset of the scored columns of a full-text index. | +| `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 the same column with different parsers, create one full-text index per parser and select the index with the `USE_INDEX` hint. See [Select a parser for a scored column](#select-a-parser-for-a-scored-column). +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: @@ -60,7 +60,7 @@ INTERSECT SELECT id FROM t WHERE FTS_MATCH_WORD('database', description); ``` -In a multi-column query, each column is tokenized by the parser defined for that column in the index, 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. +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 @@ -142,7 +142,51 @@ For the full scoring formula and parameters, see [Relevance scoring algorithm](/ ## Select a parser for a scored column -A query is tokenized by the parser of the full-text index it runs on. To search one column with more than one parser, create a separate full-text index for each parser, then select the index with the `USE_INDEX` hint: +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; @@ -151,22 +195,16 @@ ALTER TABLE t ADD FULLTEXT INDEX idx_fts_ngram (content_text) ``` ```sql --- Substring matching: the NGRAM index matches 'hand' inside 'HandleRequest' SELECT /*+ USE_INDEX(t, idx_fts_ngram) */ * FROM t WHERE FTS_MATCH_WORD('hand', content_text); --- Complete token matching: the MULTILINGUAL index matches whole tokens only SELECT /*+ USE_INDEX(t, idx_fts_ml) */ * FROM t WHERE FTS_MATCH_WORD('database', content_text); ``` -The `WITH PARSER` clause is accepted only in an index definition, as part of `FULLTEXT INDEX (col) WITH PARSER parser_name`. It is not supported inside `FTS_MATCH_WORD()`, and writing it there returns a syntax error. - -An index provides only one parser per column, so separate indexes are the only way to search one column with both complete-token and substring matching. For the underlying restriction, see [Index limitations](/ai/reference/full-text-search-limitations.md#index-limitations). - > **Note:** > -> Selecting the index selects the parser, which changes the result set. This makes parser selection part of query semantics, not performance tuning. Automatic index selection does not compare parsers, so when a scored column has indexes with different parsers, always specify the index with `USE_INDEX`. See [Automatic index selection](#automatic-index-selection). +> 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 @@ -188,8 +226,10 @@ FROM t WHERE FTS_MATCH_WORD('database', content_text); | Scenario | Behavior | | :-- | :-- | -| The indexes differ only in parser | The hint selects the parser, so the result set changes. This is the supported way to route a query between parsers. | +| 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`. | @@ -216,7 +256,7 @@ Without hints, the optimizer selects a full-text index by the following prioriti | 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. When one column has full-text indexes with different parsers, the automatically selected index determines the matching behavior of the query without any warning, so specify the index with `USE_INDEX`. +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. diff --git a/ai/reference/full-text-search-index.md b/ai/reference/full-text-search-index.md index feeebb593744f..4bfcd4e403f80 100644 --- a/ai/reference/full-text-search-index.md +++ b/ai/reference/full-text-search-index.md @@ -72,7 +72,7 @@ Attributes fall into two categories: 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. -- Assign one parser attribute to each scored column. Declaring two parsers on one column, such as `content_text WITH (multilingual, ngram(...))`, creates the index without an error, but a query can run on only one of them and there is no way to select the other, so a query that expects the unused parser returns no rows. To search one column with several parsers, create a separate full-text index for each parser. See [Multiple indexes on one table](#multiple-indexes-on-one-table). +- 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). @@ -164,7 +164,7 @@ To search across multiple scored columns, list them in the `FTS_MATCH_WORD()` ca ## 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 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 @@ -174,7 +174,7 @@ 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. When indexes on the same column use different parsers, specify the index explicitly: automatic selection does not compare parsers, so the matching behavior of the query is not what you intend. See [Choose a full-text index at query time](/ai/reference/full-text-search-functions-tidb.md#choose-a-full-text-index-at-query-time). +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 diff --git a/ai/reference/full-text-search-limitations.md b/ai/reference/full-text-search-limitations.md index 5bd03321a1c77..c9cb5d6eb74df 100644 --- a/ai/reference/full-text-search-limitations.md +++ b/ai/reference/full-text-search-limitations.md @@ -17,7 +17,7 @@ This document describes the known limitations of full-text search in TiDB. - 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. -- Declaring more than one parser attribute on a single column of the same index, such as `content_text WITH (multilingual, ngram(...))`, succeeds but does not give you both matching behaviors: a query runs on one of the parsers and cannot select the other. Create one full-text index per parser instead. +- 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 @@ -73,7 +73,7 @@ This document describes the known limitations of full-text search in TiDB. WHERE s.score > 0.5; ``` -- When `FTS_MATCH_WORD()` appears in the `SELECT` list, the `WHERE` clause must contain the same call, and `ORDER BY` must either repeat that call or reference its alias: +- 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 @@ -86,7 +86,9 @@ This document describes the known limitations of full-text search in TiDB. 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. +- 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: @@ -94,7 +96,10 @@ This document describes the known limitations of full-text search in TiDB. 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. +- 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.