Sphinx(及其分支 Manticore Search)建立全文索引的核心流程可抽象為四個階段的管線處理,每階段輸出傳遞給下一階段。
輸入:資料來源(MySQL/PostgreSQL/XML/TSV/JSON/自定義 XMLPipe2)
動作:
# sphinx.conf 片段
source src_main {
type = mysql
sql_host = localhost
sql_user = search
sql_pass = secret
sql_db = myapp
sql_query = SELECT id, title, content, category_id, tags, created_at FROM articles WHERE status=1
sql_attr_uint = category_id
sql_attr_timestamp = created_at
sql_attr_multi = uint tag from query; SELECT article_id, tag_id FROM article_tags
}
輸入:原始文檔文本
核心組件:Tokenizer(分詞器)
處理步驟:
# 中文分詞配置範例
index idx_main {
source = src_main
path = /var/lib/sphinx/idx_main
charset_table = 0..9, A..Z->a..z, _, a..z, U+4E00..U+9FFF # 保留中文字元
ngram_len = 1 # 單字切分(粗糙)
# 或整合 jieba:
# morphology = libstemmer_zh # 需編譯支援
}
輸入:Token 流
核心組件:Linguistic Processor(語言處理器)
處理步驟:
輸出:標準化 Term(詞項),帶有位置、文檔 ID、字段資訊
輸入:Term 序列
核心組件:Indexer(索引器)
核心資料結構:
# 索引器關鍵配置
index idx_main {
# ... 前述配置 ...
# 索引類型
type = plain # 或 rt (Real-Time 即時索引)
# 記憶體限制(索引建立時使用)
indexer {
mem_limit = 256M
}
# 壓縮選項
# docinfo = extern # 屬性外部儲存(預設)
# inplace_enable = 1 # 就地更新(RT 索引)
}
# 1. 全量重建(首次或結構變更)
indexer --all --rotate --config /etc/sphinx/sphinx.conf
# 2. 增量更新(主索引 + 增量索引架構)
# 主索引:每日重建
indexer --rotate idx_main --config /etc/sphinx/sphinx.conf
# 增量索引:每 5 分鐘更新
indexer --rotate idx_delta --config /etc/sphinx/sphinx.conf
# 搜尋時合併查詢
# index idx_main idx_delta
# 3. 合併索引(離線合併增量至主索引)
indexer --merge idx_main idx_delta --rotate --config /etc/sphinx/sphinx.conf
| 參數 | 作用 | 建議值 |
|---|---|---|
| charset_table | 字元分類表,決定分詞邊界 | 含中文範圍 U+4E00..U+9FFF |
| ngram_len | N-gram 分詞窗口大小 | 中文 1 或 2;英文 0(關閉) |
| morphology | 詞幹提取器列表 | stem_en, stem_ru, libstemmer_* |
| stopwords | 停用詞檔案路徑 | 每行一詞,UTF-8 編碼 |
| wordforms | 同義詞/詞形映射 | 格式:原詞 > 目標詞 |
| min_word_len | 最小索引詞長度 | 1 (中文) 或 2 (英文) |
| html_strip | 是否剝離 HTML 標籤 | 1 (開啟) |
| index_exact_words | 是否索引原始詞(支援精確匹配) | 1 |
| overshort_step | 過短詞位置增量 | 1 |
| stopword_step | 停用詞位置增量 | 1 |
# RT 索引配置(無需重建,支援即時 INSERT/REPLACE/DELETE)
index rt_main {
type = rt
path = /var/lib/sphinx/rt_main
rt_mem_limit = 512M
# 欄位定義(對應 SQL 欄位)
rt_field = title
rt_field = content
rt_attr_uint = category_id
rt_attr_timestamp = created_at
rt_attr_multi = uint tag
}
# PHP 客戶端即時寫入
$client = new SphinxClient();
$client->SetServer('127.0.0.1', 9312);
$doc = [
'id' => 12345,
'title' => '新文章標題',
'content' => '文章內容...',
'category_id' => 5,
'created_at' => time(),
'tag' => [10, 20, 30],
];
$client->AddDocument($doc); // 即時可搜尋
Sphinx 索引建立是**文檔 → 分詞 → 語言處理 → 索引**的管線流程。關鍵成功因素: