/** * sphinx search */ public function sphinxSearch(Request $request, \SphinxClient $sphinx) { $search = $request->get('search'); //sphinx的主机名和端口 //mysql -h 127.0.0.1 -P 9306 $sphinx->SetServer('127.0.0.1', 9312); //设定搜索模式 SPH_MATCH_ALL(匹配所有的查询词) $sphinx->SetMatchMode(SPH_MATCH_ALL); //设置返回结果集为数组格式 $sphinx->SetArrayResult(true); //匹配结果的偏移量,参数的意义依次为:起始位置,返回结果条数,最大匹配条数 $sphinx->SetLimits(0, 20, 1000); //最大搜索时间 $sphinx->SetMaxQueryTime(10); //索引源是配置文件中的 index 类,如果有多个索引源可使用,号隔开:'email,diary' 或者使用'*'号代表全部索引源 $result = $sphinx->query($search, '*'); //返回值说明 total 本次查询返回条数 total_found 一共检索到多少条 docs 在多少文档中出现 hits——共出现了多少次 //关闭查询连接 $sphinx->close(); //打印结果 /*echo "<pre>"; print_r($result); echo "</pre>";exit();*/ $ids = [0]; if (!empty($result)) { foreach ($result['matches'] as $key => $val) { $ids[] = $val['id']; } } $ids = implode(',', array_unique($ids)); $list = DB::select("SELECT * from documents WHERE id IN ({$ids})"); if (!empty($list)) { foreach ($list as $key => $val) { $val->content = str_replace($search, '<span style="color: red;">' . $search . '</span>', $val->content); $val->title = str_replace($search, '<span style="color: red;">' . $search . '</span>', $val->title); } } return view('/sphinx.search')->with('data', array('total' => $result['total'] ? $result['total'] : 0, 'time' => $result['time'] ? $result['time'] : 0, 'list' => $list)); }
public function getResultByTag($keyword = "", $offset = 0, $limit = 0, $searchParams = array()) { $sphinx = $this->config->item('sphinx'); $query = array(); $cl = new SphinxClient(); $cl->SetServer($sphinx['ip'], $sphinx['port']); // 注意这里的主机 $cl->SetConnectTimeout($sphinx['timeout']); $cl->SetArrayResult(true); // $cl->SetIDRange(89,90);//过滤ID if (isset($searchParams['provice_sid']) && $searchParams['provice_sid']) { $cl->setFilter('provice_sid', array($searchParams['provice_sid'])); } if (isset($searchParams['city_sid']) && $searchParams['city_sid']) { $cl->setFilter('city_sid', array($searchParams['city_sid'])); } if (isset($searchParams['piccode']) && $searchParams['piccode']) { $cl->setFilter('piccode', array($searchParams['piccode'])); } if (isset($searchParams['recent']) && $searchParams['recent']) { $cl->SetFilterRange('createtime', time() - 86400 * 30, time()); //近期1个月 } if (isset($searchParams['searchtype']) && $searchParams['searchtype']) { //精确:模糊 $searchtype = SPH_MATCH_ALL; } else { $searchtype = SPH_MATCH_ANY; } $cl->SetLimits($offset, $limit); $cl->SetMatchMode($searchtype); // 使用多字段模式 $cl->SetSortMode(SPH_SORT_EXTENDED, "@weight desc,@id desc"); $index = "*"; $query = $cl->Query($keyword, $index); $cl->close(); return $query; }