萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

用 PHP 與 Sphinx 構建高性能站內搜索引擎

當網站內容高度專業化、數據量達百萬級、或需要複雜的全文檢索(如屬性過濾、排序、分組、高亮)時,MySQL 的 LIKE 或全文索引已難以滿足。Sphinx Search 是專為此設計的開源全文檢索引擎,支援 SQL 介面、實時索引、分佈式集群,與 PHP 結合可構建極速站內搜尋。本文從架構選型到實戰部署全流程解析。

為什麼選 Sphinx?

對比項MySQL 全文索引ElasticsearchSphinx / Manticore
部署複雜度低(內建)高(JVM、集群)低(單二進制、無依賴)
資源佔用佔用 DB 資源極高(Heap 4GB+)低(幾百 MB 即可跑百萬文檔)
檢索功能基礎極強(聚合、向量、圖)強(屬性過濾、排序、分組、片段生成)
實時索引即時近實時(1s)RT 索引準實時(毫秒級)
PHP 整合原生 SQL官方客戶端官方 PHP API / PDO (MySQL 協議)
學習曲線平陡峭中等

結論:中小型專業站點、電商屬性篩選、CMS 站內搜尋,Sphinx/Manticore 是性價比最高的選擇。

架構概覽

+----------+     SQL/HTTP      +-----------+     MySQL Protocol     +----------+
|  PHP App | ─────────────────▶ |  Sphinx   | ◀───────────────────── |  MySQL   |
|          |   搜尋請求/結果    |  Searchd  |      實時索引同步       |  (主庫)   |
+----------+                   +-----------+                        +----------+
                                      ▲
                                      | XMLPipe2 / CSV / TSV / JSON
                                      ▼
                              +-----------------+
                              |  數據源         |
                              | (MySQL/Postgre/ |
                              |  XML/CSV/JSON)  |
                              +-----------------+

安裝與部署

1. 安裝 Manticore Search (Sphinx 現代分支,積極維護)

# Ubuntu/Debian
wget https://repo.manticoresearch.com/manticore-repo.noarch.deb
dpkg -i manticore-repo.noarch.deb
apt update && apt install manticore

# Docker (推薦生產)
docker run -d --name manticore \
  -p 9306:9306 -p 9308:9308 -p 9312:9312 \
  -v /data/manticore:/var/lib/manticore \
  manticoresearch/manticore:latest

2. 核心配置 /etc/manticore/manticore.conf

# 實時索引:支援 INSERT/REPLACE/DELETE 即時生效
index products_rt {
    type = rt
    path = /var/lib/manticore/data/products_rt
    rt_mem_limit = 256M
    
    # 全文欄位
    rt_field = title
    rt_field = description
    rt_field = tags
    
    # 屬性欄位(用於過濾、排序、分組)
    rt_attr_uint = category_id
    rt_attr_uint = brand_id
    rt_attr_float = price
    rt_attr_timestamp = created_at
    rt_attr_bool = is_active
    rt_attr_multi = attr_ids FROM FIELD; # 多值屬性(如顏色、規格ID)
    
    # 分詞設定
    morphology = stem_en, stem_zh  # 英文詞幹+中文分詞(需插件)
    min_word_len = 1
    charset_table = 0..9, A..Z->a..z, _, U+4E00..U+9FFF  # 保留中英文數字下劃線
    ngram_len = 1
    ngram_chars = U+4E00..U+9FFF  # 中文單字分詞
}

# 普通索引:批量重建,查詢效能略高
index products_main {
    source = products_src
    path = /var/lib/manticore/data/products_main
    morphology = stem_en, stem_zh
    # ... 其他同 rt
}

source products_src {
    type = mysql
    sql_host = 127.0.0.1
    sql_user = sphinx_user
    sql_pass = secret
    sql_db = my_shop
    sql_port = 3306
    sql_query_pre = SET NAMES utf8mb4
    sql_query = \
        SELECT id, title, description, tags, \
               category_id, brand_id, price, created_at, is_active \
        FROM products \
        WHERE is_deleted = 0
    sql_attr_uint = category_id
    sql_attr_float = price
    sql_attr_timestamp = created_at
    sql_attr_bool = is_active
}

indexer {
    mem_limit = 512M
}

searchd {
    listen = 9306:mysql41  # MySQL 協議端口,可用 PDO 連接
    listen = 9312          # 原生 SphinxAPI 端口
    listen = 9308:http     # HTTP JSON API 端口
    log = /var/log/manticore/searchd.log
    query_log = /var/log/manticore/query.log
    read_timeout = 5
    max_children = 30
    workers = thread_pool
}

PHP 整合:三種連接方式

方式一:官方 SphinxAPI (PECL sphinx)

<?php
$cl = new SphinxClient();
$cl->SetServer('127.0.0.1', 9312);
$cl->SetConnectTimeout(1);
$cl->SetArrayResult(true);
$cl->SetMatchMode(SPH_MATCH_EXTENDED2);
$cl->SetLimits(0, 20);
$cl->SetSortMode(SPH_SORT_RELEVANCE);

$cl->SetFilter('category_id', [12, 15]);
$cl->SetFilterRange('price', 100, 5000);
$cl->SetSelect('*, WEIGHT() as weight');

$result = $cl->Query('無線藍牙耳機', 'products_rt');
if ($result === false) {
    throw new Exception('Search error: ' . $cl->GetLastError());
}
// $result['matches'] 包含文檔 ID、權重、屬性值
?>

方式二:PDO MySQL 協議(推薦,無額外擴展依賴)

<?php
$pdo = new PDO('mysql:host=127.0.0.1;port=9306;charset=utf8', '', '', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

$keyword = '無線藍牙耳機';
$categoryIds = [12, 15];
$minPrice = 100;
$maxPrice = 5000;
$limit = 20;
$offset = 0;

// SphinxQL 查詢語法
$sql = "
    SELECT id, title, price, category_id, WEIGHT() AS weight
    FROM products_rt
    WHERE MATCH(:keyword)
      AND category_id IN (" . implode(',', array_fill(0, count($categoryIds), '?')) . ")
      AND price BETWEEN ? AND ?
      AND is_active = 1
    ORDER BY WEIGHT() DESC, created_at DESC
    LIMIT :offset, :limit
    OPTION ranker=proximity_bm25, field_weights=(title=10, description=5, tags=3)
";

$params = array_merge([$keyword], $categoryIds, [$minPrice, $maxPrice, $offset, $limit]);
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$results = $stmt->fetchAll();

foreach ($results as $row) {
    echo "ID:{$row['id']} | {$row['title']} | ¥{$row['price']} | 權重:{$row['weight']}\n";
}
?>

方式三:HTTP JSON API (Manticore 專有,功能最全)

<?php
$client = new GuzzleHttp\Client(['base_uri' => 'https://127.0.0.1:9308/']);

$response = $client->post('json/search', [
    'json' => [
        'index' => 'products_rt',
        'query' => [
            'bool' => [
                'must' => [['match' => ['title' => '無線藍牙耳機']]],
                'filter' => [
                    ['terms' => ['category_id' => [12, 15]]],
                    ['range' => ['price' => ['gte' => 100, 'lte' => 5000]]],
                    ['term' => ['is_active' => true]],
                ],
            ],
        ],
        'limit' => 20,
        'offset' => 0,
        'sort' => [['_score' => 'desc'], ['created_at' => 'desc']],
        'highlight' => ['fields' => ['title' => [], 'description' => []]],
    ],
]);
$data = json_decode($response->getBody(), true);
// $data['hits']['hits'] 包含高亮片段
?>

資料同步策略

策略實現方式延遲適用場景
定時重建普通索引 cron 每小時 indexer --rotate products_main 分鐘~小時 數據變更頻率低、可容忍延遲
實時索引 (RT) 應用層寫入 DB 後,同步 INSERT INTO products_rt ... 毫秒級 電商、即時發布、高一致性要求
Binlog 同步 使用 Canal/Maxwell 解析 MySQL Binlog 寫入 Sphinx 秒級 不想改動應用代碼、多系統同步
混合模式 主索引 RT 實時 + 歷史大表普通索引定時合併 混合 億級數據、熱冷分離

RT 索引同步代碼範例 (Laravel Observer)

<?php
namespace App\Observers;

use App\Models\Product;
use PDO;

class ProductSearchObserver {
    private $pdo;
    
    public function __construct() {
        $this->pdo = new PDO('mysql:host=127.0.0.1;port=9306', '', '');
    }
    
    public function saved(Product $product) {
        if ($product->is_deleted) {
            $this->delete($product->id);
            return;
        }
        $this->upsert($product);
    }
    
    public function deleted(Product $product) {
        $this->delete($product->id);
    }
    
    private function upsert(Product $p) {
        $sql = "REPLACE INTO products_rt (id, title, description, tags, category_id, brand_id, price, created_at, is_active)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute([
            $p->id, $p->title, $p->description, $p->tags,
            $p->category_id, $p->brand_id, $p->price,
            $p->created_at->timestamp, $p->is_active ? 1 : 0
        ]);
    }
    
    private function delete(int $id) {
        $this->pdo->exec("DELETE FROM products_rt WHERE id = $id");
    }
}
?>

效能調優關鍵點

  1. 屬性而非全文:所有用於 WHERE、ORDER BY、GROUP BY 的欄位必須定義為 rt_attr_*,不可放入 rt_field。
  2. 權重調優:OPTION field_weights=(title=10, tags=5, description=1) 提升標題匹配權重。
  3. 分頁深度:深分頁 (LIMIT 100000, 20) 極慢。改用 searchd 設定 max_matches 或游標式分頁 (ID 排序 + 記錄上頁最大 ID)。
  4. 內存限制:rt_mem_limit 設為服務器記憶體 30-50%,避免 OOM。
  5. 中文分詞:生產環境建議編譯安裝 jieba、scws 或使用 Manticore 內建 ngram + charset_table 方案。

監控與運維

  • 關鍵指標:SHOW STATUS 查看 queries、qps、avg_query_wall、ram_used。
  • 慢查詢日誌:query_log 記錄耗時 > 100ms 的查詢,定期分析優化。
  • 索引碎片整理:RT 索引長期增刪改會產生碎片,定期 OPTIMIZE INDEX products_rt(會阻塞寫入,建議低峰期執行)。
  • 備份:直接備份 path 目錄下的索引文件,或使用 mysqldump 導出 RT 索引數據重建。

總結

Sphinx/Manticore 以輕量、高效、SQL 兼容著稱,是 PHP 站內搜尋的最佳拍檔。掌握 RT 索引實時同步、SphinxQL 查詢優化、屬性設計 三大核心,即可構建支撐百萬級文檔、毫秒級響應的專業搜尋系統。對於更大規模、需向量搜尋、複雜聚合的場景,再考慮遷移至 Elasticsearch/OpenSearch。

copyright © 萬盛學電腦網 all rights reserved