> ## Documentation Index
> Fetch the complete documentation index at: https://villagesql.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 在 MySQL 中使用 BM25 进行带排名的全文搜索

> 如何使用 VillageSQL 的 vsql_textsearch 扩展，通过 BM25 按与搜索查询的相关性对 MySQL 行排名：DOC 列、bm25 索引、过滤器，以及可用的查询形式。

> [card] [VillageSQL is a drop-in replacement for MySQL with extensions.](https://villagesql.com/docs/en/8.4/stable/install-server.md)
>
> All examples on this page work on VillageSQL. Install Now →

> [!NOTE]
>
> 本指南需要从 `main` 分支构建的 VillageSQL 服务器，构建方法见[从源代码构建](https://villagesql.com/docs/en/8.4/dev/source.md)。0.0.8 版本没有 `vsql_textsearch` 所使用的索引扫描接口。

帮助中心的搜索框收到的只是几个词，例如 `reset password`，却必须把最有用的文章排在第一位。`LIKE '%password%'` 会读取每一行，而且不做任何排名。`vsql_textsearch` 扩展增加了 `bm25` 索引，它使用 BM25（Lucene 所用的排名函数）对行排名，并优先返回最匹配的结果。本指南会建立一张小型的帮助文章表，对它进行搜索，并用过滤器缩小结果范围。

## 开始之前

`vsql_textsearch` 使用预览能力，因此请先开启预览能力。该设置会立即生效：

```sql theme={null}
SET PERSIST vsql_allow_preview_extensions = ON;
```

该扩展不随服务器捆绑提供。请按照 [vsql\_textsearch 页面](https://villagesql.com/docs/en/extensions/vsql-textsearch.md#install)的说明构建它，然后安装：

```sql theme={null}
INSTALL EXTENSION vsql_textsearch;
```

## 创建可以搜索的表

该扩展对存放在它自己的列类型 `DOC(n)` 中的文本建立索引，这种类型最多可保存 `n` 字节的 UTF-8 文本，`n` 的取值范围是 1 到 16303。`VARCHAR` 或 `TEXT` 列不能建立 `bm25` 索引。请将 `n` 设为接近您最长文档的长度，因为每个值都会占用一条 `n + 2` 字节的完整记录。

创建表，并在表仍为空时创建索引：

```sql theme={null}
CREATE DATABASE helpdesk;
USE helpdesk;

CREATE TABLE articles (
  id    INT PRIMARY KEY,
  title VARCHAR(200) NOT NULL,
  body  DOC(2000)
);

CREATE INDEX idx_articles_body ON articles (body)
  USING EXTENDED(vsql_textsearch.bm25)
  WITH (analyzer = 'english');
```

> [!WARNING]
>
> 不要在已有行的表上运行 `CREATE INDEX`。这会触发 InnoDB 断言并使服务器停止。要为已有的行建立索引，请参阅[为已有的文本建立索引](#index-text-you-already-have)。

`english` 分析器会将文本转为小写，去掉 `the` 和 `to` 这类常见的英文单词，并将每个单词还原为词干，因此 `resetting` 和 `reset` 可以匹配。

## 加载文章

```sql theme={null}
INSERT INTO articles VALUES
  (1, 'Reset a forgotten password',
      'To reset your password, open the sign-in page and choose Forgot password. We email you a reset link that expires after one hour.'),
  (2, 'Change your email address',
      'Open account settings and enter the new email address. We send a confirmation link to the new address before the change takes effect.'),
  (3, 'Two-factor authentication',
      'Turn on two-factor authentication in account settings. After you enter your password, the sign-in page asks for a code from your authenticator app.'),
  (4, 'Export your data',
      'Account owners can export every project as a CSV file from the billing and data page. Large exports arrive by email as a download link.'),
  (5, 'Locked out after too many attempts',
      'After five failed password attempts, the account locks for fifteen minutes. Wait, then sign in again, or reset your password to unlock it at once.'),
  (6, 'Update billing details',
      'Change the card on file from the billing page. Invoices are emailed to the billing contact on the first day of each month.');
```

## 搜索并排名

按 `bm25_distance` 排序，并给出 `LIMIT`。该查询由索引提供服务，并优先返回最匹配的结果：

```sql theme={null}
SELECT id, title, bm25_distance(body, 'reset password') AS score
FROM articles
ORDER BY bm25_distance(body, 'reset password')
LIMIT 3;
```

```
+----+------------------------------------+---------------------+
| id | title                              | score               |
+----+------------------------------------+---------------------+
|  1 | Reset a forgotten password         | -2.3688040718940173 |
|  5 | Locked out after too many attempts | -2.0332278509241264 |
|  3 | Two-factor authentication          | -0.6931471805599453 |
+----+------------------------------------+---------------------+
```

`bm25_distance` 是符号取反后的 BM25 分数，因此值越小表示匹配得越好，升序排列会把最匹配的结果排在最前面。只要某一行包含搜索文本中的任意一个词，它就会被匹配。第 3 篇文章只提到了一次 `password`，没有提到 `reset`，因此排在最后。当没有任何行包含其中任何一个词时，查询返回空结果。

`EXPLAIN` 显示该查询由 `bm25` 索引提供服务：

```sql theme={null}
EXPLAIN SELECT id FROM articles
ORDER BY bm25_distance(body, 'reset password')
LIMIT 3;
```

```
+----+-------------+----------+------------+----------+---------------+-------------------+---------+------+------+----------+----------------------+
| id | select_type | table    | partitions | type     | possible_keys | key               | key_len | ref  | rows | filtered | Extra                |
+----+-------------+----------+------------+----------+---------------+-------------------+---------+------+------+----------+----------------------+
|  1 | SIMPLE      | articles | NULL       | knn_scan | NULL          | idx_articles_body | 2013    | NULL |    3 |   100.00 | Knn_hints: limit = 3 |
+----+-------------+----------+------------+----------+---------------+-------------------+---------+------+------+----------+----------------------+
```

## 必须包含、排除以及匹配短语

要缩小结果范围，请用 `bm25_query(search_text, filter)` 传入一个过滤器。扫描只返回与过滤器匹配的行，这些行仍按搜索文本排名，因此 `LIMIT` 只对匹配的行计数。请先将查询存入用户变量，因为 `bm25_distance` 只接受来自用户变量或预处理语句参数的查询：

```sql theme={null}
SET @q = bm25_query('reset password', 'email');

SELECT id, title, bm25_distance(body, @q) AS score
FROM articles
ORDER BY bm25_distance(body, @q)
LIMIT 3;
```

```
+----+----------------------------+---------------------+
| id | title                      | score               |
+----+----------------------------+---------------------+
|  1 | Reset a forgotten password | -2.3688040718940173 |
+----+----------------------------+---------------------+
```

过滤器使用与 PostgreSQL 的 `tsquery` 类似的运算符：

* `email` 匹配包含 `email` 的行。
* `reset password` 匹配同时包含这两个词的行，因为空格表示 AND。
* `email | code` 匹配包含其中任意一个词的行。
* `!code` 匹配不包含 `code` 的行。
* `"reset link"` 匹配包含该短语的行。
* `auth*` 匹配包含以 `auth` 开头的词的行。

要排除关于身份验证器验证码的文章：

```sql theme={null}
SET @q = bm25_query('password', '!code');

SELECT id, title
FROM articles
ORDER BY bm25_distance(body, @q)
LIMIT 3;
```

```
+----+------------------------------------+
| id | title                              |
+----+------------------------------------+
|  5 | Locked out after too many attempts |
|  1 | Reset a forgotten password         |
+----+------------------------------------+
```

要求结果必须包含搜索中的每一个词时，请在过滤器中重复这些词：

```sql theme={null}
SET @q = bm25_query('reset password', 'reset password');

SELECT id, title
FROM articles
ORDER BY bm25_distance(body, @q)
LIMIT 3;
```

```
+----+------------------------------------+
| id | title                              |
+----+------------------------------------+
|  1 | Reset a forgotten password         |
|  5 | Locked out after too many attempts |
+----+------------------------------------+
```

## 让索引保持最新

`INSERT`、`UPDATE` 和 `DELETE` 会让索引保持最新，因此不需要重建索引，搜索就能看到修改后的文章：

```sql theme={null}
UPDATE articles
SET body = 'Change the card on file from the billing page. Invoices are emailed to the billing contact on the first day of each month. To cancel, choose Cancel plan on the same page.'
WHERE id = 6;

SELECT id, title
FROM articles
ORDER BY bm25_distance(body, 'cancel plan')
LIMIT 3;
```

```
+----+------------------------+
| id | title                  |
+----+------------------------+
|  6 | Update billing details |
+----+------------------------+
```

## 为已有的文本建立索引

如果您的文章已经存放在一张带有 `TEXT` 列的表中，请新建一张带有 `DOC` 列的表，在它为空时建立索引，然后用 `INSERT ... SELECT` 把行复制进去：

```sql theme={null}
CREATE TABLE old_articles (
  id    INT PRIMARY KEY,
  title VARCHAR(200) NOT NULL,
  body  TEXT
);
INSERT INTO old_articles VALUES
  (1, 'Cancel a subscription',
      'Cancel your subscription from the billing page. Your plan stays active until the end of the billing period.');

CREATE TABLE articles_search (
  id    INT PRIMARY KEY,
  title VARCHAR(200) NOT NULL,
  body  DOC(2000)
);
CREATE INDEX idx_search_body ON articles_search (body)
  USING EXTENDED(vsql_textsearch.bm25)
  WITH (analyzer = 'english');

INSERT INTO articles_search SELECT id, title, body FROM old_articles;

SELECT id, title
FROM articles_search
ORDER BY bm25_distance(body, 'cancel subscription')
LIMIT 3;
```

```
+----+-----------------------+
| id | title                 |
+----+-----------------------+
|  1 | Cancel a subscription |
+----+-----------------------+
```

超过 `DOC` 列长度的值会使插入失败，并返回 `ERROR 3219 (HY000): DOC: text longer than the column's length`，因此请按您最长文档的长度来确定列的大小。

您复制的值必须是列、字面量或用户变量。在 `SELECT` 中使用 `CONCAT(title, ' ', body)` 这样的表达式会失败：

```
ERROR 3219 (HY000): Incorrect DOC value: cannot implicitly cast string expression. Use explicit conversion for column 'body' at row 1
```

要为计算得出的文本建立索引，请先把它存入一个 `TEXT` 列，然后再复制该列。

## 应避免的查询形式

计算分数需要索引扫描的统计信息，因此 `bm25_distance` 只能用在由 `bm25` 索引提供服务的查询中：按升序 `ORDER BY bm25_distance(...)`，带有 `LIMIT`，并且查询中每一处 `bm25_distance` 都使用相同的搜索文本。不带 `LIMIT` 的查询会失败：

```sql theme={null}
SELECT id, title FROM articles ORDER BY bm25_distance(body, 'password');
```

```
ERROR 3200 (HY000): VDF error in function 'bm25_distance': bm25_distance() needs the index statistics: use it in a query ordered by bm25_distance() on a bm25-indexed column, with the same query text
```

只要查询仍由 `bm25` 索引提供服务，`WHERE` 子句就可以使用。另一个索引（例如主键）上的范围条件会让优化器改用该索引，查询会失败并返回同样的错误：

```sql theme={null}
SELECT id, title
FROM articles
WHERE id < 4
ORDER BY bm25_distance(body, 'password')
LIMIT 3;
```

```
ERROR 3200 (HY000): VDF error in function 'bm25_distance': bm25_distance() needs the index statistics: use it in a query ordered by bm25_distance() on a bm25-indexed column, with the same query text
```

带有语法错误的过滤器（例如 `bm25_query('password', '"reset')` 中未闭合的引号）会失败并返回 `ERROR 3219 (HY000): InnoDB: Custom type operation failed. See server error log for details.`。服务器错误日志会指出具体的错误。

## 清理

完成后删除该数据库：

```sql theme={null}
DROP DATABASE helpdesk;
```

## 另请参阅

* [vsql\_textsearch 扩展](https://villagesql.com/docs/en/extensions/vsql-textsearch.md)：构建步骤、索引选项和当前的限制
* [MySQL 中的全文搜索](https://villagesql.com/docs/zh/guides/full-text-search.md)：MySQL 内置的 `FULLTEXT` 索引和 `MATCH ... AGAINST`
* [MySQL 中的三元组相似度](https://villagesql.com/docs/zh/guides/trigram-similarity.md)：匹配拼写错误的单词，这是 BM25 做不到的
* [索引的工作原理](https://villagesql.com/docs/zh/guides/mysql-indexes.md)：MySQL 在其他所有场景中使用的 B 树索引


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.