21人参与 • 2025-04-21 • Mysql
在mysql中,match……against是全文索引(full-text index)的查询语法,它允许你对文本进行高效的全文搜素,支持自然语言搜索和布尔搜索模式。以下是match……against的详细用法和示例
在需要使用全文索引的列上创建全文索引
示例:
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');
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;
the
、and
等)。可以通过修改ft_stopword_file
参数自定义停用词列表。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
分词器。到此这篇关于mysql match against工具详细用法的文章就介绍到这了,更多相关mysql match against工具内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论