TP通过sphinxapi接口实现全文搜索
2021-09-28 16:59:24

1.首先先在服务器上安装好sphinx并且建立好索引文件,具体安装步骤参考以下链接

windows下: https://www.cnblogs.com/life_lt/p/15348746.html

linux下:https://www.cnblogs.com/life_lt/p/15348533.html

2.下载 sphinxapi.php(点击下载)并且放入到自己的项目中

3.调用接口,代码如下

public function getSphinxData(){
 
        $searchWord = "元旦";
        
        $sp=new SphinxClient();
        $sp->SetServer('127.0.0.1',9312);
        $sp->SetArrayResult(true);
        $sp->SetMatchMode(SPH_MATCH_ALL);
        $sp->SetSortMode(SPH_SORT_ATTR_DESC,'updatetime');  //排序字段
        $sp->SetLimits(0,200);  //条数限制为200条
 
        $res=$sp->Query($searchWord,'newindex');  //通过索引查找索索结果,newindex为配置中的索引名称        
 
     
        if(isset($res['matches'])&&count($res['matches'])>0)
        {
 
            $sql='select * from yourtable where id in(';
            
 
            foreach ($res['matches'] as $v)
            {
                $sql.=$v['id'].',';
            }
            $sql=trim($sql,',').')';
 
            
            $searchModel = M('search');  //实例化model,这里是我自己程序中的实例化,用的时候改成自己的操作
            $result = $searchModel->fetchAll($sql); //查库操作,fetchAll()是我自己定义的方法,改成自己数据库操作即可
            
            $total = $res['total']; //查询到的总量
 
            $finalResult = array('result'=>$result,'total'=>$total);
 
            
            print_r($finalResult);
 
 
        }
        else
        {
            return 0;
        }
        
 
    }

结果展示:

Array
(
    [error] => 
    [warning] => 
    [status] => 0
    [fields] => Array
        (
            [0] => title
            [1] => img_cover
            [2] => url_link
            [3] => ispublish
        )
 
    [attrs] => Array
        (
            [sid] => 1
            [updatetime] => 2
        )
    
    //匹配结果
    [matches] => Array
        (
            [0] => Array
                (
                    [id] => 79476
                    [weight] => 2613
                    [attrs] => Array
                        (
                            [sid] => 718737
                            [updatetime] => 1543464537
                        )
 
                )
 
            [1] => Array
                (
                    [id] => 79475
                    [weight] => 2613
                    [attrs] => Array
                        (
                            [sid] => 718736
                            [updatetime] => 1543464085
                        )
 
                )
 
        )
 
    [total] => 117  //查询结果总量
    [total_found] => 117
    [time] => 0.000
    [words] => Array
        (
            [元] => Array
                (
                    [docs] => 625
                    [hits] => 638
                )
 
            [旦] => Array
                (
                    [docs] => 122
                    [hits] => 124
                )
 
        )

最终返回结果如下

 

本文摘自 :https://www.cnblogs.com/


更多科技新闻 ......