您的位置:首页 > 编程语言 > PHP开发

yii2中sphinx搜索 多条件选择搜索

2016-07-27 21:05 639 查看
案例要求,效果图



首先,你需要安装spinx,具体安装可以百度一份如何安装,网上有很多,就不说了,

那么,安装完成后,打开sphinx(即你所建的sphinx安装目录),

找到这个文件,sphinx/etc/csft_mysql.conf文件,



在编译器中,打开这个文件,修改sphinx的源文件,配置



改完配置后,停止sphinx服务,打开cmd,进入到你安装的sphinx安装目录中

建立索引,



索引建立成功,开启sphinx服务

在使用sphinx之前,你需要把sphinx/api/sphinxapi.php文件,复制一份,放到yii2的web中,

与你的入口文件保持同级,方便调用

创建控制器,

[html]
view plain
copy

<?php  
  
namespace frontend\controllers;  
  
use Yii;  
use app\models\Position;  
//use yii\data\Pagination;//分页类  
  
use yii\db\Query;//搜索类  
  
class IndexController extends \yii\web\Controller  
{  
  
    //下拉选项字段 搜索值  
    public function actionSearch_val()  
    {  
        $set = Yii::$app->request->get('set','');//接收搜索类型  
        $key = Yii::$app->request->get('key','');//接收值  
        require ( "sphinxapi.php" );//引入类  
        if(yii::$app->request->isAjax){  
            //echo $key.$set;die;  
            $cl = new SphinxClient ();  
            $cl->SetServer ( '127.0.0.1', 9312);   
            $cl->SetConnectTimeout ( 3 );  
            $cl->SetArrayResult ( true );  
                if(empty($key)){  
                    $cl->SetMatchMode ( SPH_MATCH_FULLSCAN );  
                }else{  
                    $cl->SetMatchMode ( SPH_MATCH_EXTENDED2 );  
                    if($set == 1){  
                        $key = $key;    
                    }else if($set == 2){  
                        $key = '@post_tempt ' .$key;  
                    }else if($set == 3){  
                        $key = '@ask_for ' .$key;    
                    }   
                }  
                $res = $cl->Query ( $key, "mysql" );  
                  
                if($res['total_found'] > 0){  
                    $ids = [];  
                    foreach ( $res['matches'] as $key => $row ) {  
                        $ids[] = $row['id'];  
                    }  
                    $query = new Query();  
                    $list = $query->select('j_id, post_tempt, ask_for')->from('job')->where(['in', 'j_id', $ids])->all();  
                    //print_r($list);  
                } else {  
                    $list = [];  
                }          
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;  
                return ['list' => $list ];  
            }  
        return $this->render('search2');  
    }  

然后,在Views对应控制器的文件夹下,创建一个文件,search2.php

[html]
view plain
copy

<?php  
  
use yii\bootstrap\ActiveForm;  
use yii\helpers\Html;  
use yii\helpers\Url;  
  
?>  
<form action="" method="get">  
    <input type="hidden" name="_csrf" value="dkZkUVdiTl8lDxQCZip9Ky4eLx4mViIWQXALAQMMOR4BEQMOZVZ8aA==">  
  
    <div class="col-md-1">  
        <select id="set">  
            <option value="1">全部</option>  
            <option value="2">标题</option>  
            <option value="3">内容</option>  
        </select>  
    </div>  
    <div class="col-md-3">  
        <input type="text" class="form-control" placeholder="keyword" id="key">  
    </div>  
    <button type="button" class="btn btn-default">Search</button>  
</form>  
  
<p>  
  
<div id="content"></div>      
  
<?php $this->beginBlock('index') ?>  
  
$(function(){  
    $('.btn-default').click(function(){  
        var set = $('#set').val();  
        var key = $('#key').val();  
        var url = '<?php echo Url::toRoute(['index/search_val'])?>';  
  
        $.getJSON(url, {'key':key, 'set':set}, function(data){  
            //alert(data);  
            console.log(data);  
            var lists= data.list;  
            //console.log(data.length)  
              
            var html = '<table class="table">';//这里用的是拼接  
            for(var i = 0; i < lists.length; i++ ) {  
                html += '<tr>';  
                html += '<td>'+lists[i].j_id+'</td>';  
                html += '<td>'+lists[i].post_tempt+'</td>';  
                html += '<td>'+lists[i].ask_for+'</td>';  
                html += '</tr>';  
            }   
            html += '</table>';  
            $('#content').html(html);  
              
        });  
    });  
});  
<?php $this->endBlock('index') ?>  
<?php $this->registerJs($this->blocks['index'], \yii\web\View::POS_END);?>

另外一种方法

public function actionSphinx(){

$request = \yii::$app->request;

if($request->isPost){

$arr = $request->post();

$sphinx = new SphinxClient();

$sphinx -> SetServer('127.0.0.1',9312);

 

$sphinx->SetMatchMode ( SPH_MATCH_EXTENDED2 );

 

//$res=$sphinx->Query("@name zhangsan","mysql");

 

$res=$sphinx->Query("@".$arr['field'].' '.$arr['search'],"mysql");

//$wh = $sphinx -> Query($arr['search'],$arr['field']);

 

/*$sphinx->SetMatchMode ( SPH_MATCH_EXTENDED2 );  */

//$res=$sphinx->Query("@name zhangsan","mysql");//查询的字段第二参数是你配置文件里面写得规则这里是*就会匹配所有规则

print_r($res);die;//打印数据

 

$wh = implode(',',array_keys($wh['matches']));

$where = "id in ($wh)";

$new = Exam::find()->where($where)->asArray()->All();

echo json_encode($new);

}else{

$this ->layout = false;

return $this ->render('sphinx');

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  搜索 sphinx php