> ## 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.

# BM25 による MySQL の順位付き全文検索

> 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]
>
> このガイドには、[ソースからのビルド](https://villagesql.com/docs/en/8.4/dev/source.md)の説明に従って `main` ブランチからビルドした VillageSQL サーバーが必要です。0.0.8 リリースには、`vsql_textsearch` が使うインデックススキャンのインターフェースがありません。

ヘルプセンターの検索ボックスには `reset password` のような数語が入力され、最も役に立つ記事を先頭に表示しなければなりません。`LIKE '%password%'` はすべての行を読み、順位付けは行いません。`vsql_textsearch` 拡張機能は `bm25` インデックスを追加します。このインデックスは、Lucene が使う順位付け関数である BM25 で行を順位付けし、最もよく一致する行を先に返します。このガイドでは、ヘルプ記事の小さなテーブルを作成し、それを検索し、フィルタで結果を絞り込みます。

## 始める前に

`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)` のテキストをインデックス化します。`DOC(n)` は最大 `n` バイトの UTF-8 テキストを保持し、`n` は 1 から 16303 までです。`VARCHAR` 列や `TEXT` 列には `bm25` インデックスを作成できません。すべての値が `n + 2` バイトのレコード全体を使うので、`n` は最も長いドキュメントに近い値を選びます。

テーブルを作成し、テーブルがまだ空のうちにインデックスを作成します。

```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` が 1 回含まれていますが、`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
```

`WHERE` 句は、`bm25` インデックスが引き続きクエリを処理する限り機能します。主キーのような別のインデックスに対する範囲条件があると、オプティマイザは代わりにそのインデックスを使い、クエリは同じエラーで失敗します。

```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/ja/guides/full-text-search.md): MySQL 組み込みの `FULLTEXT` インデックスと `MATCH ... AGAINST`
* [MySQL のトライグラム類似度](https://villagesql.com/docs/ja/guides/trigram-similarity.md): スペルを間違えた単語の一致。これは BM25 では行えません
* [インデックスの仕組み](https://villagesql.com/docs/ja/guides/mysql-indexes.md): MySQL がそれ以外のすべての用途に使う B ツリーインデックス


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