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

Coreseek (Sphinx 中文版) 全文搜索部署實戰:中文分詞、索引構建與 PHP 整合

     編輯:PHP 相關知識

為什麼選 Coreseek?

  • Sphinx 原版不支援中文分詞,需二次開發
  • Coreseek 集成 MMSEG 中文分詞,開箱即用
  • RPM/DEB 包安裝簡單,避免源碼編譯坑點

環境與安裝

# CentOS/RHEL 示例
yum install -y mmseg coreseek
# 或下載 RPM 手動安裝
rpm -ivh mmseg-*.rpm coreseek-*.rpm

中文詞典構建

  1. 獲取詞典文件:unigram.txt(官方提供,可自行添加業務詞彙如「名卡」)
  2. 生成二進制詞庫:
    mmseg -u unigram.txt  # 生成 unigram.txt.uni
    mv unigram.txt.uni uni.lib  # 重命名為 Sphinx 識別名
  3. 放置路徑:/var/mmseg/data/(對應 sphinx.conf 中 charset_dictpath)

核心配置文件 sphinx.conf 詳解

source tmsgs
{
    type = mysql
    sql_host = localhost
    sql_user = root
    sql_pass = 1
    sql_db = phpwind75sp3
    sql_port = 3306
    sql_query_pre = SET NAMES gbk
    sql_query = SELECT id, name, type, stock FROM pw_tools
    sql_attr_uint = stock
}

index tmsgsindex
{
    source = tmsgs
    path = /var/mmseg/searchdata/beihai365
    docinfo = extern
    charset_type = zh_cn.gbk
    charset_dictpath = /var/mmseg/data
    min_word_len = 2
}

indexer
{
    mem_limit = 128M
}

searchd
{
    listen = 9312
    log = /var/log/searchd.log
    query_log = /var/log/query.log
    read_timeout = 5
    max_children = 30
    pid_file = /var/log/searchd.pid
    max_matches = 1000
}

關鍵配置項說明

參數作用建議值
charset_type指定中文分詞類型zh_cn.gbk / zh_cn.utf8
charset_dictpathMMSEG 詞典目錄含 uni.lib 的目錄
sql_query_pre查詢前設置連接編碼SET NAMES gbk/utf8
sql_attr_uint整數屬性(可用於過濾/排序)stock, category_id 等
min_word_len最小索引詞長度2(中文單字也可檢索)

索引構建與服務管理

# 構建所有索引
csft-indexer --all
# 構建單個索引
csft-indexer tmsgsindex

# 啟動搜索服務
csft-searchd
# 停止
csft-searchd --stop
# 測試查詢
csft-search "名卡"

PHP 客戶端整合

<?php
require_once 'sphinxapi.php';

$cl = new SphinxClient();
$cl->SetServer('localhost', 9312);
$cl->SetMatchMode(SPH_MATCH_ALL);
$cl->SetArrayResult(true);

$res = $cl->Query('名卡', '*');
print_r($res);
/*
輸出示例:
Array
(
    [matches] => Array
        (
            [0] => Array
                (
                    [id] => 8
                    [weight] => 1
                    [attrs] => Array ( [stock] => 100 )
                )
        )
    [total] => 1
    [total_found] => 1
    [time] => 0.018
    [words] => Array ( [名卡] => Array ( [docs] => 1 [hits] => 1 ) )
)
*/

常見問題排查

現象原因對策
啟動報 charset_dictpath 錯誤詞典路徑錯誤或 uni.lib 缺失確認路徑、重新 mmseg -u 生成
搜不到中文sql_query_pre 編碼與數據庫不一致統一 SET NAMES utf8/gbk
索引巨大未設置屬性、全字段索引只索引需搜索字段,其餘用 sql_attr_*
查詢慢max_children 過小/無緩存調大 max_children、啟用查詢緩存

生產化建議

  1. 使用 Systemd 管理 searchd 進程,開機自啟
  2. 定時任務 csft-indexer --rotate --all 增量重建(需配置 sql_query_range)
  3. 監控 query_log 分析慢查詢、熱詞
  4. 高可用:雙機熱備 + VIP 漂移或 DNS 輪詢

總結

Coreseek 以 MMSEG 解決中文分詞難題,配合 Sphinx 高性能檢索引擎,是中文全文搜索的經典選型。掌握詞典構建、配置調優、索引輪轉與 PHP 整合,可快速落地業務級搜索服務。

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