《PHP教程:PHP redis實(shí)現(xiàn)超迷你全文檢索》要點(diǎn):
本文介紹了PHP教程:PHP redis實(shí)現(xiàn)超迷你全文檢索,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP實(shí)戰(zhàn)情景: 我們平臺有好多游戲, 運(yùn)營的同事在查詢某一款游戲的時候, 目前使用的是html的select下拉列表的展現(xiàn)形式, 運(yùn)營的同事得一個個去找,然后選中,耗時又費(fèi)眼
PHP實(shí)戰(zhàn)效果: 輸入"三國"或者"國三", 將自動列出所有包含"三國"的游戲名字, 輸入不限順序; 例如輸入"殺三國",仍然會將"三國殺"這款游戲找出來
PHP實(shí)戰(zhàn)實(shí)現(xiàn): 我用redis的集合+PHP的array_intersect()和mb系列函數(shù), 實(shí)現(xiàn)了一個超迷你的全文檢索功能
PHP實(shí)戰(zhàn)原理: (大道不過兩三言,說穿不值一文錢,哈哈)
PHP實(shí)戰(zhàn)1、將所有的游戲名字讀出來,拆分成單個漢字
PHP實(shí)戰(zhàn)2、 將這些漢字作為redis集合的鍵,寫入redis,每個集合里的值是所有那些游戲名字中包含此漢字的游戲的id
PHP實(shí)戰(zhàn)3、當(dāng)用戶輸入文字的時候通過ajax異步請求,將用戶輸入傳給PHP
PHP實(shí)戰(zhàn)4、將輸入的文字拆分成單個漢字, 分別找到這些漢字在redis中的集合值
PHP實(shí)戰(zhàn)5、取出來,求交集,就找到了同時包含這幾個漢字的游戲的id
PHP實(shí)戰(zhàn)6、最后到數(shù)據(jù)庫里查出來相應(yīng)的游戲信息即可
PHP實(shí)戰(zhàn)缺點(diǎn): 刪除數(shù)據(jù)不方便
PHP實(shí)戰(zhàn)PHP寫入redis和檢索的代碼:
PHP實(shí)戰(zhàn)
//自動補(bǔ)全
//不限輸入漢字的前后順序: 輸入"國三殺" => 輸出 "三國殺"
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); //求交集,因?yàn)閭魅氲膮?shù)個數(shù)不確定,因此不能直接求交集
}
}
$arrGame = $this->gamemodel->getGameNameForAutoComplate($arrGid);
// var_dump($arrGame);exit;
$jsonGame = json_encode($arrGame);
exit($jsonGame);
}
//自動補(bǔ)全, 建立索引
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);
}
}
}
PHP實(shí)戰(zhàn)操作redis的方法
PHP實(shí)戰(zhàn)
//自動補(bǔ)全功能
public function setAutoComplate($key, $value)
{
$youxikey = 'youxi_'.$key;
$this->sAdd($youxikey, $value);
}
//自動補(bǔ)全功能
public function getAutoComplate($key)
{
$youxikey = 'youxi_'.$key;
return $this->sMembers($youxikey);
}
PHP實(shí)戰(zhàn)以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持維易PHP.
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/1520.html