> ## 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 확장을 사용해 MySQL 행을 검색 쿼리와의 관련성에 따라 BM25로 순위화하는 방법: 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`를 한 번 언급하고 `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/ko/guides/full-text-search.md): MySQL에 내장된 `FULLTEXT` 인덱스와 `MATCH ... AGAINST`
* [MySQL의 트라이그램 유사도 검색](https://villagesql.com/docs/ko/guides/trigram-similarity.md): BM25가 하지 않는, 철자가 틀린 단어 매칭
* [MySQL 인덱스의 동작 방식](https://villagesql.com/docs/ko/guides/mysql-indexes.md): MySQL이 그 밖의 모든 것에 사용하는 B-트리 인덱스


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