温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在PHP中利用redis实现全文检索

发布时间:2021-02-13 17:12:54 来源:亿速云 阅读:243 作者:Leah 栏目:开发技术

怎么在PHP中利用redis实现全文检索?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

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

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

关于怎么在PHP中利用redis实现全文检索问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI