Sphinx 是高效能全文檢索引擎,支援 SQL/XML 資料源、分散式索引、即時索引、多語言分詞。本文以 Windows 為例,詳述安裝、配置中文 ngram 分詞、建立索引、PHP API 查詢全流程。
searchd.exe, indexer.exe, sphinxapi.php)D:\sphinx\D:\sphinx\data\, D:\sphinx\log\sphinx.conf.in 為 D:\sphinx\bin\sphinx.confsource src1
{
type = mysql
sql_host = localhost
sql_user = root
sql_pass = your_password
sql_db = test
sql_port = 3306
sql_query_pre = SET NAMES utf8mb4
sql_query = SELECT id, title, content, group_id, UNIX_TIMESTAMP(created_at) AS date_added FROM documents
sql_attr_uint = group_id
sql_attr_timestamp = date_added
}
index test1
{
source = src1
path = D:/sphinx/data/test1
charset_type = utf-8
# ngram 中文分詞:字元級 (1-gram)
ngram_len = 1
ngram_chars = U+3000..U+2FA1F
# 亦可加入英文單字分詞
# charset_table = 0..9, A..Z->a..z, _, a..z, U+410..U+42F->U+430..U+44F, U+430..U+44F
}
indexer
{
mem_limit = 256M
}
searchd
{
listen = 9312
listen = 9306:mysql41 # MySQL 協議介面
log = D:/sphinx/log/searchd.log
query_log = D:/sphinx/log/query.log
read_timeout = 5
max_children = 30
pid_file = D:/sphinx/log/searchd.pid
# Windows 必須關閉 seamless_rotate
# seamless_rotate = 1
}
# 1. 匯入測試資料 (隨 Sphinx 附贈 example.sql)
mysql -u root -p test < D:/sphinx/example.sql
# 2. 建立索引
D:\sphinx\bin\indexer.exe --all --config D:\sphinx\bin\sphinx.conf
# 3. 命令列測試 (注意:cmd 預設編碼 GBK,中文查詢請用 PHP API)
D:\sphinx\bin\search.exe --config D:\sphinx\bin\sphinx.conf "test"
# 前景執行 (測試用)
D:\sphinx\bin\searchd.exe --config D:\sphinx\bin\sphinx.conf --console
# 生產環境建議註冊為 Windows 服務
sc create SphinxSearch binPath= "D:\sphinx\bin\searchd.exe --config D:\sphinx\bin\sphinx.conf --servicename SphinxSearch"
sc start SphinxSearch
<?php
require_once 'D:/sphinx/api/sphinxapi.php';
$client = new SphinxClient();
$client->SetServer('127.0.0.1', 9312);
$client->SetConnectTimeout(3);
$client->SetArrayResult(true); // 回傳關聯陣列
$client->SetMatchMode(SPH_MATCH_EXTENDED2);
$client->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
// 中文查詢
$result = $client->Query('中文全文檢索', 'test1');
if ($result === false) {
die('查詢失敗: ' . $client->GetLastError());
}
echo "找到 {$result['total']} 筆,耗時 {$result['time']} 秒\n";
foreach ($result['matches'] as $doc) {
echo "ID: {$doc['id']} | Weight: {$doc['weight']} | Attrs: " . json_encode($doc['attrs']) . "\n";
}
// 釋放
$client->Close();
?>
| 需求 | 配置方案 |
|---|---|
| 即時索引 (資料變更即可搜尋) | 使用 RT (RealTime) index,配合 INSERT/REPLACE/DELETE SQL 指令操作 |
| 分散式搜尋 (多台機器) | 定義 type = distributed 索引,指定 local 和 agent 節點 |
| 關鍵字高亮 | $client->SetHighlightOptions(['before_match' => '', 'after_match' => '']); |
| 過濾屬性 | $client->SetFilter('group_id', [1, 3]); |
| 排序 | $client->SetSortMode(SPH_SORT_ATTR_DESC, 'date_added'); |
charset_type = utf-8、ngram_len = 1、ngram_chars 覆蓋 CJK 區塊;PHP 檔案存為 UTF-8 無 BOM;資料庫連線 SET NAMES utf8mb4。SET NAMES utf8。listen 埠或關閉衝突程序。log 目錄寫入權限、pid_file 路徑是否存在。Sphinx 在 Windows 上部署相對簡單,關鍵在於正確配置 ngram 中文分詞與 UTF-8 編碼鏈路。掌握 indexer 重建索引與 searchd 服務管理,即可為應用提供毫秒級全文檢索能力。生產環境建議遷移至 Linux 並啟用 systemd 管理。