萬盛學電腦網

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

PHP + Redis 實現超輕量全文檢索:中文分字 + 集合交集查詢

面對幾千款遊戲名稱的後台搜尋,原生 LIKE %keyword% 效能不佳且不支援語序不敏感。本文展示如何利用 Redis Set (集合) + PHP array_intersect 實現「輸入『殺三國』找到『三國殺』」的迷你全文檢索,零依賴 Elasticsearch,部署極簡。

核心原理:倒排索引 + 集合交集

  1. 建立索引:將每個遊戲名稱拆分為單字,以字為 Key 建立 Redis Set,值為遊戲 ID。
    例:三 → {101, 205, 312}, 國 → {101, 408}, 殺 → {101, 555}
  2. 查詢:使用者輸入關鍵字 → 拆分單字 → 取出各字對應的 Set → 求交集 → 得到同時包含所有字的遊戲 ID → 回資料庫撈詳細資訊。

PHP 實作程式碼 (CodeIgniter 風格)

建立索引 (離線/定時執行)

function setAutoComplate() {
    $arrGame = $this->gamemodel->getAllGameNameForAutoComplate(); // [id => name]
    $arrIndex = [];
    foreach ($arrGame as $gid => $gname) {
        $len = mb_strlen($gname, 'UTF-8');
        for ($i = 0; $i < $len; $i++) {
            $char = mb_substr($gname, $i, 1, 'UTF-8');
            $arrIndex[$char][] = $gid;
        }
    }
    $this->load->library('iredis');
    foreach ($arrIndex as $char => $gids) {
        foreach ($gids as $gid) {
            $this->iredis->setAutoComplate($char, $gid); // SADD youxi_字 gid
        }
    }
}

即時搜尋 (AJAX 呼叫)

function getAutoComplate() {
    $word = $this->input->post('word'); // 如 '三國'
    if (empty($word)) exit('0');

    $len = mb_strlen($word, 'UTF-8');
    $this->load->library('iredis');

    if ($len == 1) {
        $arrGid = $this->iredis->getAutoComplate($word); // 直接取單字 Set
    } else {
        $arrGid = [];
        for ($i = 0; $i < $len; $i++) {
            $char = mb_substr($word, $i, 1, 'UTF-8');
            $tmp = $this->iredis->getAutoComplate($char);
            $arrGid = empty($arrGid) ? $tmp : array_intersect($arrGid, $tmp); // 逐字交集
        }
    }

    $arrGame = $this->gamemodel->getGameNameForAutoComplate($arrGid);
    exit(json_encode($arrGame));
}

Redis 操作封裝 (iredis library)

public function setAutoComplate($key, $value) {
    $this->sAdd('youxi_' . $key, $value); // SADD
}
public function getAutoComplate($key) {
    return $this->sMembers('youxi_' . $key); // SMEMBERS
}

優缺點分析

優點缺點
零額外基建,僅需 Redis + PHP刪除/更新資料需掃描所有字集合移除 ID,維護成本高
查詢延遲極低 (亞毫秒級)不支援詞頻排序、相關性評分、模糊拼音
天然支援「語序不敏感」 (交集不分先後)單字高頻 (如「的」「遊戲」) 會導致交集龐大,需停用詞過濾
記憶體效率高 (Set 自動去重)資料量超過百萬級建議改用 Redisearch 模組或 Elasticsearch

適用場景

  • 後台管理介面:幾千~幾萬筆實體 (商品、遊戲、文章、用戶) 的快速搜尋。
  • 關鍵字聯想/自動完成。
  • 中小型專案不想引入 ELK/ES 運維負擔。

進階優化建議

  • 建立索引時過濾停用詞 (「的」「是」「在」等)。
  • 對高頻字 (出現文檔數 > 總數 50%) 不建索引或標記為停用字。
  • 使用 Redis Pipeline 批次寫入索引,大幅縮短建立時間。
  • 查詢前先按字的文檔頻度升序排列,優先交集最小的 Set,提早縮小結果集。

「大道至簡」,對於中小規模中文全文檢索需求,Redis Set + PHP 交集是極具性價比的解決方案。

copyright © 萬盛學電腦網 all rights reserved