sphinx搜索php代码实现
来源:原创
时间:2017-05-09
作者:脚本小站
分类:PHP
public function search() { if($_POST['s']) { $word = $_POST['s']; $sphinx = new \SphinxClient (); $sphinx->SetServer ( '127.0.0.1', 9312); $sphinx->SetConnectTimeout ( 3 ); $sphinx->SetArrayResult ( true ); $sphinx->SetMatchMode ( SPH_MATCH_ANY ); // $sphinx->setRankingMode(SPH_RANK_PROXIMITY_BM25);// 统计相关度计算模式 // SPH_SORT_RELEVANCE 模式, 按相关度降序排列(最好的匹配排在最前面) $sphinx->SetSortMode ( SPH_SORT_RELEVANCE ); // $sphinx->SetSortMode ( SPH_SORT_EXTENDED ,"@weight DESC,atime DESC" ); $sphinx->SetLimits(0,20); // 设置字段权重 // $sphinx->setFieldWeights(array('title'=>2000)); $result = $sphinx->Query ( $word, 'article_zhuqiyang' ); // 查询出结果 $where['id'] = array('in',array_column($result['matches'],'id')); $list = M('article')->field('id,title,atime')->where($where)->select(); // 装饰结果集 $title = array_column($list,'title'); $title = $sphinx->BuildExcerpts($title,'article_zhuqiyang',$word,array( 'before_match' => '<font color="red">', 'after_match' => '</font>' )); $weight = array_column($result['matches'],'weight','id'); $list_count = count($list); for ($i = 0; $i < $list_count; $i++){ $list[$i]['title'] = $title[$i]; $list[$i]['weight'] = $weight[$list[$i]['id']]; } usort($list, function($a, $b) { $aw = $a['weight']; $bw = $b['weight']; $aa = $a['atime']; $ba = $b['atime']; if($aw == $bw){ if($aa == $ba){ return 0; } return ($aa < $ba) ? 1 : -1; } return ($aw < $bw) ? 1 : -1; }); $this->assign('list',$list); } $this->display(); }