php实现sphinx,php利用sphinxapi接口来实现全文搜索

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 "最终返回结果")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值