MySQL 8中使用全文检索示例
首先建议张册测试用的表test
,并使用fulltext
说明将title
和body
两列的数据加入全文检索的索引列中:
drop table if exists test;
create table test (
id integer not null primary key auto_increment,
title varchar(50),
body longtext,
fulltext(title, body) with parser ngram
);
然后往其中插入数据:
insert into test (title, body) values
('金缕衣', '劝君莫惜金缕衣,劝君惜取少年时。花开堪折直须折,莫待无花空折枝。'),
('送别', '山中相送罢,日暮掩柴扉。春草明年绿,王孙归不归。'),
('春晓', '春眠不觉晓,处处闻啼鸟。夜来风雨声,花落知多少。'),
('江雪', '千山鸟飞绝,万径人踪灭。孤舟蓑笠翁,独钓寒江雪。'),
('何满子', '故国三千里,深宫二十年。一声何满子,双泪落君前。');
然后我们可以执行如下语句来查询“山”这个字:
select * from test where match(title, body) against ('金缕衣' in natural language mode);
结果如下:
mysql> select * from test where match(title, body) against ('金缕衣' in natural language mode);
+----+-----------+--------------------------------------------------------------------------------------------------+
| id | title | body |
+----+-----------+--------------------------------------------------------------------------------------------------+
| 1 | 金缕衣 | 劝君莫惜金缕衣,劝君惜取少年时。花开堪折直须折,莫待无花空折枝。 |
+----+-----------+--------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
或者我们可以用bool模式查看即包含“三千”又包含“二十”的数据:
select * from articles where match(title, body) against ('+三千 +二十' in boolean mode);
结果如下:
mysql> select * from test where match(title, body) against ('+三千 +二十' in boolean mode);
+----+-----------+--------------------------------------------------------------------------+
| id | title | body |
+----+-----------+--------------------------------------------------------------------------+
| 5 | 何满子 | 故国三千里,深宫二十年。一声何满子,双泪落君前。 |
+----+-----------+--------------------------------------------------------------------------+
1 row in set (0.00 sec)
更多信息请参考这篇博客,写的非常好!:https://www.jianshu.com/p/645402711dac