1小时!MySQL8.0全局搜索从入门到精通
- 配置mysql8.0的my.ini
# 配置全局搜索的分词ngram
ngram_token_size=1
innodb_ft_min_token_size = 1
ft_min_word_len = 1
- ngram_token_size配置分词大小
- 参考地址:https://dev.mysql.com/doc/refman/8.0/en/fulltext-search-ngram.html
- 官方解释(比百度强太多):
ngram token size is configurable using the ngram_token_size configuration option, which has a minimum value of 1 and maximum value of 10.
Typically, ngram_token_size is set to the size of the largest token that you want to search for. If you only intend to search for single characters, set ngram_token_size to 1. A smaller token size produces a smaller full-text search index, and faster searches. If you need to search for words comprised of more than one character, set ngram_token_size accordingly. For example, “Happy Birthday”is “生日快乐” in simplified Chinese, where “生日” is “birthday”, and “快乐” translates as “happy”. To search on two-character words such as these, set ngram_token_size to a value of 2 or higher. - innodb_ft_min_token_size 默认为3 —— 最小token size
- ft_min_word_len 默认为4 —— 搜索短语长度
- 设置好之后保存文件
- 如果之前设置过全文索引,请先清除掉,不然不会起效
- 重启mysql8.0的服务
- 给表 增加全文索引
- 语法:
ALTER TABLE 表名称
ADD FULLTEXT INDEX 索引名称 (字段1, 字段2, 字段3)
WITH PARSER ngram;ALTER TABLE operation_log ADD FULLTEXT INDEX ft_index (module, operation, manager_name) WITH PARSER ngram;
- 语法:
- 进行测试
- 语法:
SELECT * FROM 表名称
WHERE MATCH(字段1, 字段2, 字段3)
AGAINST("查询关键词")SELECT * FROM operation_log WHERE MATCH(module, operation, manager_name) AGAINST("耶" IN BOOLEAN MODE)
- 语法:
- 结果示例
- 设置搜索模式
- 自然语言模式(NATURAL LANGUAGE MODE) ,
- 自然语言模式是MySQL 默认的全文检索模式。自然语言模式不能使用操作符,不能指定关键词必须出现或者必须不能出现等复杂查询。
- BOOLEAN模式(BOOLEAN MODE)
- BOOLEAN模式可以使用操作符,可以支持指定关键词必须出现或者必须不能出现或者关键词的权重高还是低等复杂查询。
- 自然语言模式(NATURAL LANGUAGE MODE) ,
SELECT * FROM operation_log WHERE MATCH(module, operation, manager_name) AGAINST('authManagement' IN BOOLEAN MODE);
标题深得猿心~!