it编程 > 数据库 > Mysql

MySql match against工具详细用法

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;

六、全文索引的限制

七、 配置全文索引

修改最小词长度:

-- 查看当前配置
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;

九. 全文索引的性能优化

到此这篇关于mysql match against工具详细用法的文章就介绍到这了,更多相关mysql match against工具内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

MySQL索引的优化之LIKE模糊查询功能实现

04-21

Nginx配置文件的使用以及实现负载均衡的4种常用方式

04-22

nginx实现负载均衡与实例解读

04-22

利用Nginx实现资源代理和接口代理的实现方法

04-22

MySQL存储引擎InnoDB架构原理和执行流程

04-20

mysql中的group by高级用法

04-23

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论