在mysql中,match……against是全文索引(full-text index)的查询语法,它允许你对文本进行高效的全文搜素,支持自然语言搜索和布尔搜索模式。以下是match……against的详细用法和示例
一、全文索引的基本概念
- 全文索引适用于char、varchar和text类型的列
- 全文索引支持自然语言搜索和布尔搜索
- 全文索引只能用于myisam和innodb存储引擎(mysql5.6及以上版本支持innodb的全文索引)
二、创建全文索引
在需要使用全文索引的列上创建全文索引
示例:
create table articles (
id int primary key auto_increment,
title varchar(255) not null,
content text not null,
fulltext (title, content) -- 在title和content列上创建全文索引
);
三、自然语言搜索
自然语言搜索是全文索引的默认模式。它会根据搜索词的相关性返回结果
select * from table_name
where match(column1, column2, ...) against('search_term');
示例:
-- 插入数据
insert into articles (title, content) values
('mysql tutorial', 'this is a tutorial about mysql.'),
('advanced mysql', 'learn advanced techniques in mysql.'),
('postgresql vs mysql', 'a comparison between postgresql and mysql.');
-- 自然语言搜索
select * from articles
where match(title, content) against('mysql');
- 结果:
- 返回包含mysql的记录,并按相关性排序
- 相关性得分可以通过match……against的结果获取:
select id, title, match(title, content) against('mysql') as score
from articles
where match(title, content) against('mysql');
四、布尔搜索
布尔搜素允许使用特定的操作符来精确控制搜索行为
语法:
select * from table_name
where match(column1, column2, ...) against('search_term' in boolean mode);
常用操作符:
+:必须包含该词。-:必须不包含该词。*:通配符,匹配以指定词开头的词。"":短语搜索,匹配完整短语。():分组操作符。
示例:
-- 必须包含mysql,且不包含postgresql
select * from articles
where match(title, content) against('+mysql -postgresql' in boolean mode);
-- 包含mysql或postgresql
select * from articles
where match(title, content) against('mysql postgresql' in boolean mode);
-- 包含以my开头的词
select * from articles
where match(title, content) against('my*' in boolean mode);
-- 包含完整短语"mysql tutorial"
select * from articles
where match(title, content) against('"mysql tutorial"' in boolean mode);
五、相关性排序
全文索引会为每条记录计算一个相关性得分(relevance score),可以根据得分对结果进行排序。
示例:
select id, title, match(title, content) against('mysql') as score
from articles
where match(title, content) against('mysql')
order by score desc;
六、全文索引的限制
- 最小词长度:默认情况下,mysql全文索引会忽略长度小于4的词。可以通过修改ft_min_word_len(myisam)或innodb_ft_min_token_size(innodb)参数调整
- 停用词:全文索引会忽略常见的停用词(如
the、and等)。可以通过修改ft_stopword_file参数自定义停用词列表。 - 中文支持:mysql的全文索引对中文支持较差,通常需要配合分词工具(如
ngram)使用。
七、 配置全文索引
修改最小词长度:
-- 查看当前配置 show variables like 'innodb_ft_min_token_size'; -- 修改配置(需要重启mysql) set global innodb_ft_min_token_size = 2;
使用ngram分词器(支持中文):
-- 创建表时指定ngram分词器
create table articles (
id int primary key auto_increment,
title varchar(255) not null,
content text not null,
fulltext (title, content) with parser ngram
);
-- 查询时使用ngram分词器
select * from articles
where match(title, content) against('关键词' in boolean mode);
八、 删除全文索引
如果需要删除全文索引,可以使用以下语法:
alter table table_name drop index index_name;
示例:
alter table articles drop index title;
九. 全文索引的性能优化
- 索引列选择:只为需要搜索的列创建全文索引,避免不必要的索引开销。
- 分词器选择:对于中文搜索,使用
ngram分词器。 - 缓存结果:对于高频查询,可以将结果缓存到redis等缓存系统中。
到此这篇关于mysql match against工具详细用法的文章就介绍到这了,更多相关mysql match against工具内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
海报
197






