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

# vsql_textsearch extension for MySQL

> The vsql_textsearch extension adds BM25 full-text search to MySQL: a bm25 index on a DOC column that returns the rows that best match a search, ranked by relevance.

`vsql_textsearch` adds BM25 full-text search to MySQL. You store text in a
`DOC(n)` column, put a `bm25` index on it, and ask for the best matches with
`ORDER BY bm25_distance(column, 'query') LIMIT n`. The index ranks rows with
BM25, the ranking function that Lucene uses, and stems English words, so a
search for `run dog` finds a row that says `running dogs`.

| | |
| - | - |
| **Maintainer** | VillageSQL |
| **Source and full documentation** | [villagesql/vsql-textsearch](https://github.com/villagesql/vsql-textsearch) |
| **License** | GPL-2.0 |
| **Capability** | Preview |

> [!WARNING]
>
> This extension needs a VillageSQL server built from the `main` branch. The
> 0.0.8 release does not have the index scan interface that the extension
> uses. The extension also declares preview capabilities, so
> `vsql_allow_preview_extensions` must be `ON`. Start the server with
> `--vsql_allow_preview_extensions=ON`, or run
> `SET PERSIST vsql_allow_preview_extensions = ON`.

## Install

`vsql_textsearch` is not bundled with the server, so build it from the
repository first, against your server build tree:

```bash theme={null}
cmake -S . -B build -DVTS_BUILD_EXTENSION=ON -DVillageSQL_BUILD_DIR=$HOME/build/villagesql
cmake --build build -j
cmake --install build
```

`cmake --install` copies `vsql_textsearch.veb` into the server build's
`veb_output_directory`, which is the `lib/veb` directory that the server reads.
Then install it:

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

Confirm it is there:

```sql theme={null}
SELECT EXTENSION_NAME
FROM INFORMATION_SCHEMA.EXTENSIONS
WHERE EXTENSION_NAME = 'vsql_textsearch';
```

```
+-----------------+
| EXTENSION_NAME  |
+-----------------+
| vsql_textsearch |
+-----------------+
```

If `vsql_allow_preview_extensions` is `OFF`, the install fails:

```
ERROR 3219 (HY000): Failed to load VEF extension 'vsql_textsearch': extension requires preview capabilities but vsql_allow_preview_extensions is OFF
```

## What it adds

| Name | Kind | What it does |
| - | - | - |
| `DOC(n)` | column type | UTF-8 text of up to `n` bytes, where `n` is 1 to 16303. Every value takes a full record of `n + 2` bytes |
| `vsql_textsearch.bm25` | index type | A BM25 index on a `DOC` column |
| `bm25_distance(doc, query)` | function, returns a real number | The negated BM25 score of the row for the query, so the best match sorts first in ascending order |
| `bm25_query(text, filter)` | function, returns text | Packs ranked text and a Boolean filter into one query value |
| `bm25_indexes()` | function, returns JSON text | The status of every bm25 index the server has opened |
| `bm25_status(id)`, `bm25_spill(id)`, `bm25_merge(id)` | functions, return JSON text | Status of one index, and manual flush and merge |

The index takes these options in a `WITH (...)` clause. An option that you
leave out takes its default.

| Option | Default | What it controls |
| - | - | - |
| `analyzer` | `'english'` | How text is split into terms. `english` lowercases, drops English stop words, and stems |
| `k1` | `1.2` | How quickly repeated terms stop adding to the score |
| `b` | `0.75` | How much a long document is penalized |
| `memtable_docs` | `10000` | How many row versions the in-memory part holds before it is written out as a segment |
| `segments_per_level` | `8` | How many segments of one size merge into the next size |

`bm25_indexes`, `bm25_status`, `bm25_spill`, and `bm25_merge` are a temporary
interface for testing. They name an index by an internal id
(`tablespace:root page`), and they do not check privileges: an account with
only `USAGE` can call them.

## Example

Create the table and the index while the table is empty, then insert:

```sql theme={null}
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');

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

Ask for the best matches:

```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         |  -0.8242067974670295 |
|  5 | Locked out after too many attempts |  -0.6657335238173159 |
|  3 | Two-factor authentication          | -0.13221220213756243 |
+----+------------------------------------+----------------------+
```

To require or exclude words, pass a filter with `bm25_query`, through a user
variable:

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

The [ranked search guide](https://villagesql.com/docs/en/guides/bm25-search.md) covers the filter syntax,
loading rows you already have, and the query shapes that work.

## Limits

> [!WARNING]
>
> `CREATE INDEX` on a table that already has rows stops the server with an
> InnoDB assertion (`old_index != nullptr` in the error log). Create the index on an empty table, then load it with `INSERT` or
> `INSERT ... SELECT`.

* A search must be a query that the index serves: `ORDER BY
  bm25_distance(...)` in ascending order, with a `LIMIT`, and the same search
  text everywhere `bm25_distance` appears. Any other query that calls
  `bm25_distance` fails:

  ```
  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 `WHERE id < 4` on the primary key, makes
  the optimizer use that index, and the query fails with the error above.

* `bm25_query(...)` written directly inside `bm25_distance(...)` fails with an
  `Incorrect DOC value` error. Pass it through a user variable or a
  prepared-statement parameter.

* Only a `DOC` column takes a bm25 index. On `VARCHAR` or `TEXT`, `CREATE
  INDEX` fails with
  `ERROR 3219 (HY000): No default index profile found: column 'body' is not a custom type`.

* A value longer than `n` bytes fails with
  `ERROR 3219 (HY000): DOC: text longer than the column's length`.

* A `DOC` value must come from a column, a literal, or a user variable. An
  expression such as `CONCAT(...)` fails with
  `ERROR 3219 (HY000): Incorrect DOC value: cannot implicitly cast string expression. Use explicit conversion for column 'body' at row 1`.

* A bad index option or a filter with a syntax error fails with
  `ERROR 3219 (HY000): InnoDB: Custom type operation failed. See server error log for details.`
  The reason is only in the server error log.

* The stored format can change between versions of the extension.

## See also

* [Ranked full-text search with BM25](https://villagesql.com/docs/en/guides/bm25-search.md) — a worked search over a table of articles, with filters
* [Preview capabilities](https://villagesql.com/docs/en/extensions/build/preview-capabilities) — what the preview flag turns on and what it promises
* [Available extensions](https://villagesql.com/docs/en/extensions/catalog) — the full catalog
* [villagesql/vsql-textsearch](https://github.com/villagesql/vsql-textsearch) — source, build instructions, and the current limits


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