怎么在PHP中利用redis實現(xiàn)全文檢索?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
原理:(大道不過兩三言,說穿不值一文錢,哈哈)
1、將所有的游戲名字讀出來,拆分成單個漢字
2、 將這些漢字作為redis集合的鍵,寫入redis,每個集合里的值是所有那些游戲名字中包含此漢字的游戲的id
3、當用戶輸入文字的時候通過ajax異步請求,將用戶輸入傳給PHP
4、將輸入的文字拆分成單個漢字, 分別找到這些漢字在redis中的集合值
5、取出來,求交集,就找到了同時包含這幾個漢字的游戲的id
6、最后到數(shù)據(jù)庫里查出來相應的游戲信息即可
缺點:刪除數(shù)據(jù)不方便
PHP寫入redis和檢索的代碼:
//自動補全 //不限輸入漢字的前后順序: 輸入"國三殺" => 輸出 "三國殺" function getAutoComplate() { //$word = $this->input->post('word'); $word = '三國'; if (empty($word)) { exit('0'); } $intWordLength = mb_strlen($word, 'UTF-8'); $this->load->library('iredis'); if (1 == $intWordLength) { $arrGid = $this->iredis->getAutoComplate($word); } else { $arrGid = array(); for ($i=0; $i < $intWordLength; $i++) { $strOne = mb_substr($word, $i, 1, 'UTF-8'); $arrGidTmp = $this->iredis->getAutoComplate($strOne); $arrGid = empty($arrGid) ? $arrGidTmp : array_intersect($arrGid, $arrGidTmp); //求交集,因為傳入的參數(shù)個數(shù)不確定,因此不能直接求交集 } } $arrGame = $this->gamemodel->getGameNameForAutoComplate($arrGid); // var_dump($arrGame);exit; $jsonGame = json_encode($arrGame); exit($jsonGame); } //自動補全, 建立索引 function setAutoComplate() { $arrGame = $this->gamemodel->getAllGameNameForAutoComplate(); $arrIndex = array(); foreach ($arrGame as $gid => $gname) { $intGnameLength = mb_strlen($gname, 'UTF-8'); for ($i=0; $i < $intGnameLength; $i++) { $strOne = mb_substr($gname, $i, 1, 'UTF-8'); $arrIndex[$strOne][] = $gid; } } $this->load->library('iredis'); foreach ($arrIndex as $word => $arrGid) { foreach ($arrGid as $gid) { $this->iredis->setAutoComplate($word, $gid); } } }
操作redis的方法
//自動補全功能 public function setAutoComplate($key, $value) { $youxikey = 'youxi_'.$key; $this->sAdd($youxikey, $value); } //自動補全功能 public function getAutoComplate($key) { $youxikey = 'youxi_'.$key; return $this->sMembers($youxikey); }
關于怎么在PHP中利用redis實現(xiàn)全文檢索問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關知識。
文章標題:怎么在PHP中利用redis實現(xiàn)全文檢索-創(chuàng)新互聯(lián)
轉(zhuǎn)載來于:http://www.chinadenli.net/article38/cchcpp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供微信公眾號、外貿(mào)建站、網(wǎng)站設計公司、網(wǎng)站策劃、定制網(wǎng)站、網(wǎng)站建設
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容