sphinx是基于SQL的全文检索工具,能够结合MySQL、PostgreSQL做全文搜索。提供比数据库本身更专业的搜索!下面讲解下php通过sphinxapi接口实现全文搜索。
#### 安装sphinx
首先安装好sphinx并且建立好索引文件,具体安装步骤参考以下链接。
windows下:http://www.tigerbook.cn/article-127.html
linux下:http://www.tigerbook.cn/article-130.html
#### 下载 sphinxapi
下载 [sphinxapi.php](http://tigerbook.cn/demo/sphinxapi.rar "下载sphinxapi.php") 并且放入到项目中
#### 调用接口
```
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;
}
}
```
通过sphinx查询出结果结构如下
```
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
)
)
)
[total] => 117 //查询结果总量
[total_found] => 117
[time] => 0.000
[words] => Array
(
[元] => Array
(
[docs] => 625
[hits] => 638
)
[旦] => Array
(
[docs] => 122
[hits] => 124
)
)
```
最终返回结果
![最终返回结果](/uploads/content/5c136a3d75121.jpg "最终返回结果")