<?php
/**
* * @author blvming
* * @link http://www.sphinxsearch.org
* * @todo 基于thinkphp的sphinx简单扩展类,方便 逻辑层的调用。及与thinkphp配合分页使用
* * @copyright copyleft * @version 1.0 * */
import(‘Com.Sphinx.Util.Sphinxapi’);
class sphinx extends SphinxClient {
public $limit; //每页显示的数量
public $startRc; //起始记录
public function __construct($limit=25)
{ parent::SphinxClient(); //sphinx的api还是使用php4编写
if($_GET[C('VAR_PAGE')])
{ $s = $_GET[C('VAR_PAGE')] -1; }
else { $s = 0; }
$this->limit = $limit;
$this->startRc = $s*$limit;
$this->SetServer(’192.168.1.10′,3312); // ip地址及端口可放在构造函数中当参数
}
/**
+———————————————————-
* sphinx 检索
+———————————————————-
* @access public
* @param $idx string 索引名称
* @param $kw string 关键字
* @param $filter mixed 过滤条件
+———————————————————-
* @return array(‘id串’,'检索到的总数’,'花费时间’,'匹配结果’)
+———————————————————-
* @throws ThinkException
+———————————————————-
*/
public function search($idx,$kw,$filter=null)
{
$this->SetMatchMode(SPH_MATCH_ALL);
//设置过滤条件
if(!is_null($filter))
{
foreach ($filter as $attr=>$value) {
$this->SetFilter($attr,$value); //$attr为要过滤的属性,$value为属性值
}
}
$this->SetLimits($this->startRc,$this->limit,1000);
$this->SetMatchMode(SPH_MATCH_PHRASE);//使用多字段模式
$res = $this->Query ( “$kw”, $idx);
//当没有查询到数据时
if($res['total'] ==0) return false;
$idStr = implode(array_keys($res['matches']),’,');
return array(‘ids’=>$idStr,’total’=>$res['total_found'],’time’=>$res['time'],’matches’=>$res['matches']);
}
/**根据属性返回统计数据返回值如
* array(3) {
[3] => string(1) “1″
[2] => string(1) “4″
[1] => string(1) “1″
}
* 键名即为属性,值为该属性下的统计数量
*
* */
public function countByAttr($idx,$kw,$attr,$filter=null)
{
//设置过滤条件
if(!is_null($filter) && is_array($filter))
{
foreach ($filter as $attrKey=>$value) {
$this->SetFilter($attrKey,$value);
}
}
$this->SetMatchMode(SPH_MATCH_ALL);
$this->SetGroupBy($attr,SPH_GROUPBY_ATTR);
$res = $this->Query ( $kw, $idx);
$matches = $res['matches'];
$rsArr = array();
foreach ($matches as $value) {
$rsArr[$value['attrs'][$attr]] = $value['attrs']['@count'];
}
return $rsArr;
}
}
</pre>