概述:
在一堆文字中找到含有關鍵字的應用。當然也可以用以下語句實現:
select * from 《表名》 where 《欄位名》 like 『%abc%』
但是它的效率太低,是全盤掃瞄。
mysql 提供了更高效的方法全文索引(fulltext)
重要:
mysql 5.6之前版本,只有myisam支援全文索引,5.6之後,innodb和myisam均支援全文索引。
只有char、varchar、text型別欄位能建立全文索引。
當大量寫入資料時,建議先寫入資料,後再建立全文索引,提高效率。
mysql內建ngram 解析器,可以解析中日韓三國文字。有漢字的一定要啟用它。
英文分詞用空格,逗號;中文分詞用 ngram_token_size 設定,後面有講解。
全文索引在引用前需要新設定下變數
均在my.ini檔案中設定,在 [mysqld]的下面追加
需要將搜尋短語長度設定合適
// myisam
ft_min_word_len = 4; 預設值
ft_max_word_len = 84; 預設值
// innodb
innodb_ft_min_token_size = 3; 預設值
innodb_ft_max_token_size = 84; 預設值
//ngram解析器令牌長度----即aiginst()中字串切分的最小字元長度
ngram_token_size = 2~10 ; 預設值
一般設定:(以下例子均是假定設定如下)
在 [mysqld]的下面追加:
innodb_ft_min_token_size = 1
ft_min_word_len = 1
ngram_token_size = 1
設定好後需要關閉mysql服務,再重啟mysql服務。在全文查詢前,需要先將全文索引刪除(如果有),再重新建。
建立全文索引
建議建表後新建
alter table 《表名》 add fulltext index 《索引名》(欄位名1,欄位2,,) [ with parser ngram];
自然語言模式,預設,一般省略不寫
in natural language mode,
例子1:
select foldid,foldname from fold where match(foldname) against (『張三』 );
查詢包含張,或三,或張三的記錄,與『+張三』 ,張三」,+張三」 結果相同
布林搜尋模式:
in natural language mode
《+》----------必須包含此字串
《-》----------必須不包含此字串
《「 」》--------雙引號內作為整體不能拆詞
《*》---------萬用字元,匹配任意字元
例子1:
select foldid,foldname from fold where match(foldname) against (『張三』 in boolean mode);
查詢含有張三的記錄,與『+張三』,的結果都相同
例子2:
select foldid,foldname from fold where match(foldname) against (』「張三」』 in boolean mode);
查詢包含張三的記錄,「張三」作為整體,與+」張三」結果相同,與上面例一的結果也相同。
例子3:
select foldid,foldname from fold where match(foldname) against (』+「美女」 & +「動人」』 in boolean mode);
查詢有『美女』的又有『動人』的記錄,「美女"與"動人」
例子4:
select foldid,foldname from fold where match(foldname) against (』「美女」 & 「動人」』 in boolean mode);
查詢有『美女』的或有『動人』的記錄,「美女"或"動人」
查詢擴充套件搜尋,使用較少bufen
搜尋字串用於執行自然語言搜尋,然後,搜尋返回的最相關行的單詞被新增到搜尋字串,並且再次進行搜尋,查詢將返回來自第二個搜尋的行。
總結:a) 對於布林模式,預設採用整體方式。
b) 對於自然模式,預設不採用整體方式。
文中如有不正確之處還請告知:376372062@qq.com ,不勝感謝。
部分參考出處:參考出處
Mysql 使用全文索引
mysql5.6之前 fulltext索引只支援myisam的表型別,5.6開始在innodb型別中開始支援。建立全文索引需要注意,預設索引詞最小單位是4,一般都需要稍微修改一下,show variables like ft min word len 檢視預設 linux 修改 etc my.cnf...
mysql全文索引的坑 MySQL全文索引問題
我有乙個包含以下資料的 文章 mysql select from articles id title body 1 mysql tutorial dbms stands for database 2 how to use mysql well after you went through a 3 o...
mysql全文索引
了解 solr 之後 發現全文索引也能做檢索 故了解了下 筆記如下 建立全文索引 alter table table add fulltext index fulltext table 列1 列2 查詢方式 select from table where match 列1 列2 against 查詢...