MySQL 5 7 中文全文檢索使用教程

2021-09-25 08:33:27 字數 2500 閱讀 8292

在mysql 5.7.6之前,全文索引只支援英文全文索引,不支援中文全文索引,需要利用分詞器把中文段落預處理拆分成單詞,然後存入資料庫。

從mysql 5.7.6開始,mysql內建了ngram全文解析器,用來支援中文、日文、韓文分詞。

本文使用的mysql 版本是5.7.22,innodb資料庫引擎。

ngram全文解析器

ngram就是一段文字裡面連續的n個字的序列。ngram全文解析器能夠對文字進行分詞,每個單詞是連續的n個字的序列。例如,用ngram全文解析器對「生日快樂」進行分詞:

n=1: '生', '日', '快', '樂' 

n=2: '生日', '日快', '快樂'

n=3: '生日快', '日快樂'

n=4: '生日快樂'

mysql 中使用全域性變數ngram_token_size來配置ngram中n的大小,它的取值範圍是1到10,預設值是2。通常ngram_token_size設定為要查詢的單詞的最小字數。如果需要搜尋單字,就要把ngram_token_size設定為1。在預設值是2的情況下,搜尋單字是得不到任何結果的。因為中文單詞最少是兩個漢字,推薦使用預設值2。

全域性變數ngram_token_size的兩種設定方法:

1、啟動mysqld命令時

mysqld --ngram_token_size=2
2、修改mysql配置檔案

[mysqld] 

ngram_token_size=2

建立全文索引

1、建立表的同時建立全文索引

create table articles (

id int unsigned auto_increment not null primary key,

title varchar (200),

body text,

fulltext (title, body) with parser ngram

) engine = innodb;

2、通過 alter table 的方式來新增

alter table articles add fulltext index ft_index (title,body) with parser ngram;
3、直接通過create index的方式

create fulltext index ft_index on articles (title,body) with parser ngram;
全文檢索模式

示例

select * from articles

where match (title,body)

against ('一路 一帶' in natural language mode);

// 不指定模式,預設使用自然語言模式

select * from articles

where match (title,body)

against ('一路 一帶');

示例上面的示例返回結果會自動按照相關性排序,相關性高的在前面。相關性的值是乙個非負浮點數,0表示無相關性。

// 獲取相關性的值

select id,title,

match (title,body) against ('手機' in natural language mode) as score

示例

// 獲取匹配結果記錄數

select count(*) from articles

where match (title,body)

against ('一路 一帶' in natural language mode);

可以使用boolean模式執行高階查詢。

示例select * from articles

where match (title,body)

示例下面的例子演示了boolean模式下運算子的使用方式:

必須同時包含兩個詞

'"some words"'

使用雙引號把要搜素的詞括起來,效果類似於like '%some words%',

例如「some words of wisdom」會被匹配到,而「some noise words」就不會被匹配。 注意

MySQL 5 7 深度解析 中文全文檢索

全文檢索在mysql裡面很早就支援了,只不過一直以來只支援英文。緣由是他從來都使用空格來作為分詞的分隔符,而對於中文來講,顯然用空格就不合適,需要針對中文語義進行分詞。這不,從mysql 5.7開始,mysql內建了ngram全文檢索外掛程式,用來支援中文分詞,並且對myisam和innodb引擎有...

MySQL 5 7中文輸入問題

mysql 5.7,pycharm2017,資料庫輸入出現internalerror pymysql.err.internalerror 1366,u incorrect string value xe6 x8b xbf xe5 xb7 xa5.for column 的錯誤 資料庫中文輸入的錯誤 解...

mysql5 7中文亂碼問題

檢視當前mysql使用的字符集 show variables like character 結果解釋 character set client 客戶端請求資料的字符集 character set connection 客戶端與伺服器連線的字符集 character set database 資料庫伺...