首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Sphinx 全文檢索引擎 Windows 安裝與中文分詞配置完整教學

     編輯:PHP 相關知識

簡介

Sphinx 是高效能全文檢索引擎,支援 SQL/XML 資料源、分散式索引、即時索引、多語言分詞。本文以 Windows 為例,詳述安裝、配置中文 ngram 分詞、建立索引、PHP API 查詢全流程。

安裝步驟

  1. 下載:Win32 Release Binaries with MySQL support (含 searchd.exe, indexer.exe, sphinxapi.php)
  2. 解壓至 D:\sphinx\
  3. 建立資料與日誌目錄:D:\sphinx\data\, D:\sphinx\log\
  4. 複製 sphinx.conf.in 為 D:\sphinx\bin\sphinx.conf

關鍵配置 sphinx.conf (中文 ngram 完整範例)

source 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"

啟動 searchd 服務

# 前景執行 (測試用)
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 API 查詢範例 (UTF-8 編碼檔案)

<?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。
indexer 報錯 "sql_query_pre: SET NAMES utf8 failed"
MySQL 版本過舊不支援 utf8mb4,改用 SET NAMES utf8。
searchd 無法啟動 9312 埠被佔用
修改 listen 埠或關閉衝突程序。
Windows 服務啟動失敗
檢查 log 目錄寫入權限、pid_file 路徑是否存在。

總結

Sphinx 在 Windows 上部署相對簡單,關鍵在於正確配置 ngram 中文分詞與 UTF-8 編碼鏈路。掌握 indexer 重建索引與 searchd 服務管理,即可為應用提供毫秒級全文檢索能力。生產環境建議遷移至 Linux 並啟用 systemd 管理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved