摘要:
今天遇到一個奇怪的現象:通過全文檢索的方法找不到關鍵"new"的數據,但是能找到"news"、"ne"”的記錄。至於為什么找不到是以為沒有"new"這個單詞。之后在表里面看到是有new單詞的。之后測試了好久,對全文索引(fulltext)知識點進行了復習[18章],結果還是不知道原因。最后發現了一個常常被忽視的知識點,剛好是處理問題的關鍵。
方法:
查看和全索引(fulltext)相關的變量:
root@localhost : (none) 11:49:31>show variables like '%ft%'; +--------------------------+----------------+ | Variable_name | Value | +--------------------------+----------------+ | ft_boolean_syntax | + -><()~*:""&| | | ft_max_word_len | 84 | | ft_min_word_len | 2 | | ft_query_expansion_limit | 20 | | ft_stopword_file | (built-in) | +--------------------------+----------------+ 5 rows in set (0.00 sec)
看到ft_stopword_file參數,懷疑"new"在stopword里面,所以檢索不出來。而stopword 是有mysql built-in 自己控制的。嘗試自己添加stopword,並且應用於服務器。
在MySQL配置文件里面的[mysqld]選項組里添加:
ft_stopword_file = /var/lib/mysql/stopword.txt
修改stopword.txt文件的文件主和文件組:
chown -R mysql:mysql /var/lib/mysql/stopword.txt
編輯stopword.txt 文本,在里面添加(由於不知道格式,就測試了下,確認好了之后為)
#關鍵字用單引號包含,並且用逗號隔開各個關鍵字。直接在一行里寫入,不換行,如:
'a','b','c',...
因為不知道MySQL自己built-in它自己有哪寫關鍵字,所以我就直接修改stopword.txt:
#直接用空來取代之前built-in的stopword
'',''
最后重啟服務器,再查看變量:
root@localhost : (none) 11:52:39>show variables like '%ft%'; +--------------------------+-----------------------------+ | Variable_name | Value | +--------------------------+-----------------------------+ | ft_boolean_syntax | + -><()~*:""&| | | ft_max_word_len | 84 | | ft_min_word_len | 2 | | ft_query_expansion_limit | 20 | | ft_stopword_file | /var/lib/mysql/stopword.txt | +--------------------------+-----------------------------+ 5 rows in set (0.00 sec)
重新制定成功,最后需要修復檢索的表:
repair table xx;
最后,再運行之前的檢索SQL,結果就出來了。另外,經過stopword 處理以后,索引文件體積可能會減少。
SELECT * FROM xx WHERE MATCH (fulltext) AGAINST ('"new"' IN BOOLEAN MODE);
244 rows in set (0.00 sec)
相關網站:
http://dev.mysql.com/doc/refman/5.5/en/fulltext-stopwords.html