前言:
1、查询索引:show index from 表名
2、查询变量:show [global] variables
3、设置变量:set [global] 变量名=xxx
4、创建普通索引 create index 索引名 on 表名(列名)
5、创建全文缩影 create fulltext index 索引名 on 表名(列名) [索引解析器]
一、FullText全文索引
1、支持中文全文索引的版本从5.7.6开始
2、简单语法如下:match(索引列,多个用逗号分割) against('查询内容');
3、出现的位置:可以出现在 select之后,group by之后,order by之后,having之后,having之后,where之后;当出现在select之后,返回的是相似度值
4、支持的搜索类型:自然语言搜索,布尔搜索,扩展搜索
1.1 自然语言搜索
1 语法:match(索引列,多个用逗号分割) against('查询内容' [in natural language mode]);
1.2布尔搜索
1.2.1 语法:match(索引列,多个用逗号分割) against('查询内容' in Boolean mode);
1.2.1 布尔搜索支持 AND NOT OR三种,其中AND用'+'表示,NOT用'-'表示,任何操作符都不添加代表OR
1.2.3 若想将内容当成一个整体可以使用""标记,例如'"mysql"'
select * from
articles where
match(title,body) against('"we show"' in boolean mode)
1.2.4 简单实例如下
#必须出现mysql,不需要yoursql
select * from
articles where
match(title,body) against('mysql-yoursql' in boolean mode)
#mysql和yoursql必须同时出现
select * from
articles where
match(title,body) against('mysql+yoursql' in boolean mode)
1.2.5 其他方式搜索
~:消极操作符,查询词添加上该操作符时,匹配到对应查询词时,会降低其相似度
select title, body,match(title,body) against('+mysql ~YourSQL' in boolean mode) as score from articles where
match(title,body) against('+mysql ~YourSQL' in boolean mode);
*:模糊查询,不能出现在首位,例如:db*,floo*g都可以。*db不行
select title, body from articles where
match(title,body) against('foll*g' in boolean mode);
<>:降低后者提高其排名。例如:+apple +(>stands <tutorial),会匹配 apple stands或者 apple tutorial,其中apple stands 比apple tutorial的排名靠前
select title, body from articles where
match(title,body) against('+mysql +(>stands <tutorial)' in boolean mode)
1.3 扩展搜索
1 语法:match(索引列,多个用逗号分割) against('查询内容' with query expansion);
2 扩展搜索,当用户输入的搜索短语较短时,自动扩展用户的搜索意图,提供更多的搜索内容
自然语言搜索
select title, body from articles where
match(title,body) against('database' in natural language mode)
扩展搜索
select title, body from articles where
match(title,body) against('database' with query expansion)
1.4 停用词
1、 innodb引擎默认的全局停用词表:information_schema.INNODB_FT_DEFAULT_STOPWORD
2、自定义停用词表,创建一个列名为value1的表:create table my_stop(value varchar(255)) engine=innodb;
然后通过设置全局变量 set global innodb_ft_server_stopword_table='库名/自定义的表' 设置自定义的停用词表。建议在建立全局索引前创建,如果索引已经创建需要删除重新建立,持久化,可在配置文件中my.cnf配置。
3、innodb引擎中索引词的最小,最大长度可通过变量innodb_ft_min_token_size 、innodb_ft_max_token_size设置,持久化可在配置文件中my.cnf配置
1.5 支持中文分词的插件ngram
1、ngram默认的分词token数量为2,其值的取值范围可以为1-10,通过变量ngram_token_size配置,也可以在配置文件中配置
2、创建ngram全文索引:创建索引时指定解析器为ngram:create fulltext index 索引名 on 表名(列名) with parser ngram
3、使用方法可参考英文的使用方法
4、手动重建全文索引:optimize table 表名