通配符和正则表达式的限制:
性能:通常要求匹配所有行,比较耗时;
明确控制很难;
无法智能化地选择结果。
全文本搜索:
必须索引被搜索的列,而且要随着数据的改变,自动维护该索引(在增加、更新或删除时,索引随之自动更新)。
一般在创建表时启用全文本搜索:
例:
create table productnotes
(
note_id int not null auto_increment,
prod_id char not null,
note_date datetime not null,
note_text text null,
primary key(note_id),
fulltext(note_text)
)engine=myisam;
注:不要在导入数据时使用fulltext:在导入所有的数据后,定义fulltext,这样有助于更快地导入数据。
selete与match()和against()一起使用:
match():指定被搜素的列
against():指定要使用的搜索表达式
例:
selete note_text
from productnotes
where match(note_text)against('rabbit');
比较:
selete note_text
from productnotes
where note_text like '%rabbit%';
搜索结果次序不同
即:全文本搜索会对结果进行排序,具有较高等级的行先返回。
等级:由行中的词的数目,唯一词的数目、整个索引中的词的总数以及包含该词的行的数目确定(如目标词靠前的比靠后的等级高)。
查询扩展:
扩展搜索结果,可以得到和搜索有关的其他行。
例:
selete note_text
from productnotes
where match(note_text)against('anvils' with query expansion);
布尔文本搜索:
(即使没有定义fulltext索引也可以使用)
例:匹配包含heavy但不包含任意以rope开始的行
selete note_text
from productnotes
where match(note_text)against('heavy-rope*' in boolean mode);
说明:-rope*,‘-’排除,‘*’截断(可理解为用于词尾的通配符)
布尔搜索操作符
布尔操作符 | 说明 |
---|---|
+ | 包含,词必须存在 |
- | 排除,必须不能存在 |
> | 包含,且增加等级值 |
< | 包含,且减少等级值 |
() | 把词作为子表达式 |
~ | 取消一个词的排序值 |
* | 词尾的通配符 |
“” | 定义一个短语 |
例:搜索包含rabbit和bait的行
selete note_text
from productnotes
where match(note_text)against('+rabbit +bait' in boolean mode);
例:搜索至少包含rabbit和bait其中一个词的行
selete note_text
from productnotes
where match(note_text)against('rabbit bait' in boolean mode);
例:搜索包含“rabbit bait”整个短语的行(双引号)
selete note_text
from productnotes
where match(note_text)against("rabbit bait" in boolean mode);
例:匹配rabbit和bait,并增加前者的等级,降低后者的等级
selete note_text
from productnotes
where match(note_text)against('>rabbit <bait' in boolean mode);
例:匹配safe和combination,并降低后者的等级
selete note_text
from productnotes
where match(note_text)against('+safe +(<combination)' in boolean mode);
全文本搜索使用说明:
短词被忽略(<=3);
内建非用词列表;
50%的出现频率,作为非用词(不用于bool搜索);
若表中行数少于3,将不返回结果;
忽略单引号;
不是所有的引擎都支持全文本搜索。