MATCH (col1, col2, ...) AGAINST (expr [IN BOOLEAN MODE | WITH QUERY EXPANSION])
-- 自然語言模式
SELECT * FROM articles WHERE MATCH (title, body) AGAINST ('database');
-- 顯示相關度分數並排序
SELECT id, body,
MATCH (title, body) AGAINST ('Security implications of running MySQL as root') AS score
FROM articles
WHERE MATCH (title, body) AGAINST ('Security implications of running MySQL as root')
ORDER BY score DESC;
ft_min_word_len。ft_stopword_file。核心邏輯:將中文文字以雙字滑動窗口切分,如「資料庫應用」→「資料」「料庫」「庫應」「應用」。搜尋時同樣切分,達到模糊匹配。
function DV_ChineseWordSegment($str, $encodingName='gbk') {
// 1. 移除 HTML 標籤
$str = preg_replace('#<[a-zA-Z]+?.*?>|#is', '', $str);
// 2. 過濾停用字
$str = str_replace($arrStopWords['StrRepl'], ' ', $str);
$str = preg_replace($arrStopWords['PregRepl'], ' ', $str);
// 3. 英文單獨保留,中文雙字切分
$arr = explode(' ', $str);
foreach ($arr as $tmpStr) {
if (preg_match('/^[\x00-\x7f]+$/i', $tmpStr)) {
$returnVal[] = ' ' . $tmpStr; // 純英文
} else {
// 英文部分單獨提取
preg_match_all('/([a-zA-Z]+)/i', $tmpStr, $matches);
if (!empty($matches[0])) {
foreach ($matches[0] as $matche) $returnVal[] = $matche;
}
// 移除 ASCII,剩下中文進行雙字切分
$tmpStr = preg_replace('/([\x00-\x7f]+)/i', '', $tmpStr);
$strLen = $objEnc->StrLength($tmpStr) - 1;
for ($i = 0; $i < $strLen; $i++) {
$returnVal[] = $objEnc->SubString($tmpStr, $i, 2); // 雙字切分
}
}
}
return $returnVal;
}
$arrTopicIndex = DV_ChineseWordSegment($topic);
if (!empty($arrTopicIndex)) {
$topicindex = $db->escape_string(implode(' ', $arrTopicIndex));
if ($topicindex !== '') {
$db->query("UPDATE {$dv}topic_ft SET topicindex='{$topicindex}' WHERE topicid='{$RootID}'");
} else {
$db->query("DELETE FROM {$dv}topic_ft WHERE topicid='{$RootID}'");
}
}
ngram parser 支援中日韓分詞:CREATE FULLTEXT INDEX idx ON tbl(col) WITH PARSER ngram;pg_trgm、zhparser 等擴充套件。