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

# Ranked Full-Text Search in MySQL with BM25

> How to rank MySQL rows by relevance to a search query with BM25, using VillageSQL's vsql_textsearch extension: a DOC column, a bm25 index, filters, and the query shapes that work.

> [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]
>
> This guide needs a VillageSQL server built from the `main` branch, as
> [Build from source](https://villagesql.com/docs/en/8.4/dev/source.md) describes. The 0.0.8 release does not
> have the index scan interface that `vsql_textsearch` uses.

A help center search box gets a few words, such as `reset password`, and has
to put the most useful article first. `LIKE '%password%'` reads every row and
does not rank anything. The `vsql_textsearch` extension adds a `bm25` index that
ranks rows with BM25, the ranking function that Lucene uses, and returns the
best matches first. This guide builds a small table
of help articles, searches it, and narrows the results with filters.

## Before you start

`vsql_textsearch` uses preview capabilities, so turn them on first. This takes
effect at once:

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

The extension is not bundled with the server. Build it as the
[vsql\_textsearch page](https://villagesql.com/docs/en/extensions/vsql-textsearch.md#install) describes, and
then install it:

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

## Create a table you can search

The extension indexes text in its own column type, `DOC(n)`, which holds up to
`n` bytes of UTF-8 text, with `n` from 1 to 16303. A `VARCHAR` or `TEXT` column
does not take a `bm25` index. Choose `n` near your longest document, because
every value takes a full record of `n + 2` bytes.

Create the table, and create the index while the table is still empty:

```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]
>
> Do not run `CREATE INDEX` on a table that already has rows. It stops the
> server with an InnoDB assertion. To index rows you already have, see
> [Index text you already have](#index-text-you-already-have).

The `english` analyzer lowercases the text, drops common English words such as
`the` and `to`, and reduces each word to its stem, so `resetting` and `reset`
match.

## Load the articles

```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.');
```

## Search and rank

Order by `bm25_distance` and give a `LIMIT`. The index serves the query and
returns the best matches first:

```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` is the BM25 score with its sign flipped, so a lower value is a
better match and ascending order puts the best match first. The search text
matches a row that has any of its words. Article 3 mentions `password` once
and does not mention `reset`, so it ranks last. When no row has any of the
words, the query returns an empty result.

`EXPLAIN` shows that the `bm25` index serves the query:

```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 |
+----+-------------+----------+------------+----------+---------------+-------------------+---------+------+------+----------+----------------------+
```

## Require, exclude, and match phrases

To narrow the results, pass a filter with `bm25_query(search_text, filter)`.
The scan returns only the rows that match the filter, still ranked by the
search text, so `LIMIT` counts matching rows. Put the query in a user variable
first, because `bm25_distance` accepts it only from a user variable or a
prepared-statement parameter:

```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 |
+----+----------------------------+---------------------+
```

The filter uses operators like PostgreSQL's `tsquery`:

* `email` matches a row that contains `email`.
* `reset password` matches a row that contains both words, because a space means AND.
* `email | code` matches a row that contains either word.
* `!code` matches a row that does not contain `code`.
* `"reset link"` matches a row that contains the phrase.
* `auth*` matches a row that contains a word that starts with `auth`.

To exclude the articles about authenticator codes:

```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         |
+----+------------------------------------+
```

To require every word of the search, repeat the words in the filter:

```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 |
+----+------------------------------------+
```

## Keep the index current

`INSERT`, `UPDATE`, and `DELETE` keep the index current, so a search sees a
changed article without a rebuild:

```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 |
+----+------------------------+
```

## Index text you already have

When your articles already live in a table with a `TEXT` column, create a new
table with a `DOC` column, index it while it is empty, and copy the rows in
with `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 |
+----+-----------------------+
```

A value longer than the `DOC` column fails the insert with
`ERROR 3219 (HY000): DOC: text longer than the column's length`, so size the
column for your longest document.

The value you copy must be a column, a literal, or a user variable. An
expression such as `CONCAT(title, ' ', body)` in the `SELECT` fails:

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

To index computed text, store it in a `TEXT` column first, and then copy that
column.

## Query shapes to avoid

The score needs the statistics of the index scan, so `bm25_distance` works
only in a query that the `bm25` index serves: `ORDER BY bm25_distance(...)`
in ascending order, with a `LIMIT`, and the same search text everywhere
`bm25_distance` appears in the query. A query without `LIMIT` fails:

```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
```

A `WHERE` clause works while the `bm25` index still serves the query. A range
condition on another index, such as the primary key, makes the optimizer use
that index instead, and the query fails with the same error:

```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
```

A filter with a syntax error, such as an unclosed quote in
`bm25_query('password', '"reset')`, fails with
`ERROR 3219 (HY000): InnoDB: Custom type operation failed. See server error log for details.`
The server error log names the mistake.

## Clean up

Drop the database when you are done:

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

## See also

* [vsql\_textsearch extension](https://villagesql.com/docs/en/extensions/vsql-textsearch.md): the build steps, the index options, and the current limits
* [Full-text search in MySQL](https://villagesql.com/docs/en/guides/full-text-search.md): MySQL's built-in `FULLTEXT` index and `MATCH ... AGAINST`
* [Trigram similarity in MySQL](https://villagesql.com/docs/en/guides/trigram-similarity.md): matching misspelled words, which BM25 does not do
* [How indexes work](https://villagesql.com/docs/en/guides/mysql-indexes.md): the B-tree indexes that MySQL uses for everything else


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