MySQL 8中使用全文檢索示例
阿新 • • 發佈:2019-02-01
primary ans parser mat where lan uri reat article
首先建議張冊測試用的表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
MySQL 8中使用全文檢索示例