technology-note/数据库/基础/2.mysql全文检索.md
2022-01-20 16:33:50 +08:00

51 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
id: '2019-03-27-09-48'
date: '2019/03/27 09:48'
title: 'mysql全文检索'
tags: ['mysql', 'fulltext']
categories:
- '数据库'
- '基础'
---
  最近想给个人的项目加个全文检索,但是 VPS 的内存太捉急,在跑了一个 mysql几个 node和一个 java 后已经不足以再跑一个 es所以就想着在 mysql 里做全文检索。
**说明:**mysql 的全文检索速度较慢,只适合小微系统临时使用。
  从 MySQL 5.7.6 开始MySQL 内置了 ngram 全文检索插件,用于支持中文分词,并且可以在 MyISAM 和 InnoDB 中使用。
# 配置
  首先设置分词大小,修改 mysql 配置文件linux 一般在/etc/mysql/my.cnf,windows一般为 my.ini),在[mysqld]下加一行:
```properties
[mysqld]
# 通常还有其他配置,这里未列出
ngram_token_size=2
```
该值默认为 2范围1~10.
<!-- more -->
# 建立索引
&emsp;&emsp;对检索字段建立全文索引,注意要选择解析引擎-- **WITH PARSER `ngram`**,如果多多个字段检索,需建立这些字段的联合全文索引。比如下面 name 字段索引只能用于对 name 进行检索。如果要对`nameage`进行检索,需要再建立一个`nameage`的联合全文检索。
```sql
ALTER TABLE `psn`.`game`
ADD FULLTEXT INDEX `name_full_index`(`name`) WITH PARSER `ngram`;
```
# 查询语法
&emsp;&emsp;基本语法:
```sql
select id,name,description from game where match(`name`) against('小明' IN boolean MODE)
```
查询语法详见:
[https://blog.csdn.net/zwrj1130/article/details/55506179](https://blog.csdn.net/zwrj1130/article/details/55506179)