全文本搜索介绍
由于数据是索引的,全文本搜索相当快。
通配符 和 正则表达式 匹配通常要求MySQL尝试匹配 表中 所有行(而且这些搜索极少使用 表索引。 )
因此,随着被搜索的行数不断增加,这些搜索会非常耗时。
MySQL支持的数据引擎中,MyISAM 支持全文本搜索,而InnoDB不支持。
Create Table productnotes
(
note_id int not null Auto_increment,
prod_id char(10) not null,
note_date datetime not null,
note_text text null,
Primary key(note_id),
FULLTEXT(note_text)
) ENGINE = MyISAM;
---用Match() 和 Against() 执行全文本搜索
---例子
SELECT note_text
FROM productnotes
WHERE Match(note_text) Against('rabbit');
---还可以使用拓展搜索
SELECT note_text
FROM productnotes
WHERE Match(note_text) Against('rabbit' with query expansion);
布尔搜索
---使用布尔搜索
SELECT note_text
from productnotes
where Match(note_text)
Against('heavy' in boolean mode);
全文本布尔操作符
- 排除,词必须不出现
> 包含,且增加等级值
< 包含,且减少等级值
~ 取消一个词的排序值
* 词尾的通配符
” ” 定义一个短语
( ) 把词组成表达式
举例
select note_text
from productnotes
where match(note_text)
against('rabbit bait' in boolean mode);
上述代码,在rabbit 和 bait前面,没有布尔操作符。
所以,之要一行中包含rabbit 或者包含bait 就进行输出。
select note_text
from productnotes
where match(note_text)
against('+rabbit +bait' in boolean mode);
在这个代码中,rabbit 和 bait 均前存在包含操作符,所以,必须在一行中,同时存在rabbit 和 bait 才进行输出。
对全文本搜索的说明及注意事项⚠️
- 在索引全文本时,短词被忽略或被删除[短词:指具有3个或三个以下字符的词],幸运的是,这个可以更改。
- MySQL自带的内建非用词列表(stopword),其中的词在索引全文本时,会被忽略。幸运的是,可以覆盖这个列表。
- MySQL规定,如果一个词出现在50%以上的行中,则认为它为 非用词 ,从而讲起忽略。幸运的是,该规则不用于in boolean mode。
- 若表中行数少于 3行 ,则全文本搜索不返回结果。
- 忽略词中的单引号。ex: don’t 索引为dont.
- 不具有词分隔符的语言[汉语/日语等]不能正确的返回全文本搜索的结果。
- 仅在MyISAM数据库引擎中支持全文本搜索。