1、首先要设置 ngram_token_size
一种是在启动mysql的时候 mysqId --ngram_token_size=2
另一种是在配置文件里修改,通常是vi /etc/my.cnf
。然后添加一句ngram_token_size=2
,然后重启一下mysql systemctl restart mysqld.service
(我这环境是centos 7 ,mysql 5.7)。
2、创建全文索引。
CREATE TABLE posts (
id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
title VARCHAR (200),
content TEXT,
FULLTEXT (title, content) WITH PARSER ngram
) ENGINE = INNODB;
CREATE FULLTEXT INDEX ft_index ON posts (title,content) WITH PARSER ngram;
3、搜索
默认就是自然语言模式:
SELECT * MATCH (title,content) AGAINST ('你好') FROM posts;
也可以指定:
SELECT * MATCH (title,content) AGAINST ('你好 打工人' IN NATURAL LANGUAGE MODE) FROM posts;
BOOLEAN模式可以执行高级查询:
SELECT * MATCH (title,content) AGAINST ('+你好 -打工人' IN BOOLEAN MODE) FROM posts;
必须包含“你好”,且不能包含“打工人”。