php使用xunsearch分词搜索

composer下载扩展文件:

composer require --prefer-dist hightman/xunsearch "*@beta"

 

添加ini配置文件:

 

关键词搜索代码:

/**
     * 中文分词搜索
     * @param string $gamename 游戏名
     * @param bool $is_scws 是否开启中文分词(例如:口袋新世代,拆分成:口袋、新、世代)
     * @param int $limit 搜索结果条数
     * @param string $file ini文件名
     * @return array 返回结果
     * @throws \XSException
     */
    public function xunsearchGame($gamename,$is_scws = false,$limit = 100,$file = '97wan_game'){
        $xs = new \XS($file);
        if($is_scws === true) {
            //中文分词
            $tokenizer = new \XSTokenizerScws;
            $text = $gamename;
            //词语拆分
	  $words = $tokenizer->getTokens($text);
	  $where = '';
	  //拼接成查询条件(OR)
            foreach ($words as $key => $val) {
                if ($key == 0) {
                    $where = $val;
                } else {
                    $where .= ' OR ' . $val;
                }
            }
        }else {
            $where = $gamename;
        }
        $result =  $xs->search->setQuery($where)
//            ->setSort('id','asc') #按索引排序
            ->setDocOrder(true) #按添加索引排序(升序)
            ->setLimit($limit)
            ->search();
        $xs->search->close();

        $array = [];
        foreach ($result as $doc) {
            $array[] = $doc->f('id');//返回查询游戏的id
        }
        return $array;
    }

更新(新增)代码:

/**
 * 新增(更新)xunsearch数据库
 * @param array $data
 * @param int $data['id'] 游戏id
 * @param string $data['gamename'] 游戏名称
 * @return bool
 */
public function xunsearchSave($data,$file = '97wan_game'){
    try {
        $xs = new \XS($file);
        #创建文档对象
        $doc = new \XSDocument;
        $doc->setFields($data);

        #更新(新增)数据
        $index = $xs->index;
        $index->update($doc);

        #强制刷新当前索引列表数据
        $result = $index->flushIndex();

        return $result;
    }catch (\Exception $e){
        return false;
    }
}

注意:

  1. 初始化索引数据库,可采用数据库导入,或者代码逐条新增(add);
  2. 新增索引数据时,如必须及时更新的数据则需要强制更新索引,不然会有几秒钟(甚至几十秒)的缓冲更新时间;

 

参考文档地址:

看云:https://www.kancloud.cn/baidu/xunsearch/62580

官方:http://www.xunsearch.com/doc/php/guide/start.overview

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值