当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP redis实现超迷你全文检索

PHP redis实现超迷你全文检索

2017年12月12日  | 移动技术网IT编程  | 我要评论

情景: 我们平台有好多游戏, 运营的同事在查询某一款游戏的时候, 目前使用的是html的select下拉列表的展现形式, 运营的同事得一个个去找,然后选中,耗时又费眼

效果: 输入"三国"或者"国三", 将自动列出所有包含"三国"的游戏名字, 输入不限顺序; 例如输入"杀三国",仍然会将"三国杀"这款游戏找出来

实现: 我用redis的集合+php的array_intersect()和mb系列函数, 实现了一个超迷你的全文检索功能

原理: (大道不过两三言,说穿不值一文钱,哈哈)

1、将所有的游戏名字读出来,拆分成单个汉字

2、 将这些汉字作为redis集合的键,写入redis,每个集合里的值是所有那些游戏名字中包含此汉字的游戏的id

3、当用户输入文字的时候通过ajax异步请求,将用户输入传给php

4、将输入的文字拆分成单个汉字, 分别找到这些汉字在redis中的集合值

5、取出来,求交集,就找到了同时包含这几个汉字的游戏的id

6、最后到数据库里查出来相应的游戏信息即可

缺点: 删除数据不方便

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); //求交集,因为传入的参数个数不确定,因此不能直接求交集
      }
    }

    $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);
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网