class SeachAction extends Action {
public function index(){
Vendor('Coreseek.api.sphinxapi');
$q_kwd=I('get.wd','','strip_tags,htmlspecialchars');//搜索关键词
$q_kwd=trim($q_kwd);
import('ORG.Util.Page');
$PageSize=10;//分页大小
$nowPage=$this->_get('p');//当前页
$nowPage = $nowPage>1 ? $nowPage : 1;
/**
*关键词高亮显示,以及产生文本摘要
*BuildExcerpts($docs, $index, $words, $opts=array())
*参数(包含文档内容的数组,索引名,关键词,高亮参数)
**/
$opts = array(
"before_match" => "", //关键词高亮开始的html代码
"after_match" => "", //关键词高亮结束的html代码
// "limit" => 100, //摘要最多包含的符号数,默认256
// "around" => 3, //每个关键词左右选取的词的数目,默认为5
);
$sph = new SphinxClient();//实例化 sphinx 对象
$sph->SetServer('127.0.0.1','9312');//连接9312端口
$sph->SetConnectTimeout(3);//设置超时时间
//$sph->SetSortMode(SPH_SORT_RELEVANCE); //查询结果根据相似度排序
$sph->SetSortMode(SPH_SORT_EXTENDED, "@weight desc,updatetime DESC");//先按权重 再按时间排序
$sph->SetArrayResult(false);//设置结果返回格式,true以数组,false以PHP hash格式返回,默认为false
$sph->setFilter('status',array(1));
if(strlen($q_kwd)>=18){
$sph->SetMatchMode(SPH_MATCH_ALL);//如果用户查询字符大于=18个匹配有查询词
}else{
$sph->SetMatchMode(SPH_MATCH_ANY);//设置匹配方式,匹配查询词中的任意一个
}
$off=($nowPage-1)*$PageSize;
$sph->SetLimits($off,$PageSize);//传递当前页面所需的数据条数的参数
$result = $sph->Query($q_kwd,'delta;news');//执行搜索操作,参数(关键词,[索引名])
if(!array_key_exists('matches', $result)){//如果没有匹配结果,直接返回
$ids='';
$pagedata=array();
}else{
$arr_key = array_keys($result['matches']);//取出matches中的ID//获取到匹配文章的ID
$ids = implode(',',$arr_key);//数组转成字符串
$table_main='news';
$table_sub='addnews';
$sql="SELECT a.id,title,cateid,click,small_pic,updatetime,tags, b.description FROM ".$table_main." a left join ".$table_sub." b on a.id=b.id where a.id in({$ids})";
$pagedata=M()->query($sql);
}
$pagedata2=array();
foreach($pagedata as $v){
//$pagedata2[] = $sph->BuildExcerpts($v, 'news', $q_kwd, $opts);//使用高亮显示代码,使用高亮速度慢
$pagedata2[]=$v;
}
$this->pagedata =$pagedata2;
$count=$result['total'];//sphinx搜索总数
$Page = new Page($count,$PageSize);
$this->page=$Page->show();
$this->q_wd=$q_kwd;
$this->q_count=$count;
$this->totalcount=$count;//记录总数
$this->display();
}
}