然后可以使用php来调用sphinx:
sphinx查询索引出来的结果默认为一个关联数组,其中id对应的为从数据库取出来的数据库主键ID,也就是说使用sphinx的表必须存在主键,否则不能返回结果。
实例一: <?php $s = new SphinxClient; $s->setServer("127.0.0.1", 9312); $s->setMatchMode(SPH_MATCH_PHRASE); $s->setMaxQueryTime(30); $res = $s->query("宝马",'main'); #[宝马]关键字,[main]索引源source $err = $s->GetLastError(); var_dump(array_keys($res['matches'])); echo "<br>"."通过获取的ID来读取数据库中的值即可。"."<br>"; echo '<pre>'; var_dump($res); var_dump($err); echo '</pre>'; 实例二: <?php $sphinx = new SphinxClient; $sphinx->setServer("localhost", 9312); $sphinx->setMatchMode(SPH_MATCH_ANY); //匹配模式 ANY为关键词自动拆词,ALL为不拆词匹配(完全匹配) $sphinx->SetArrayResult ( true ); //返回的结果集为数组 $result = $sphinx->query("test","*"); //星号为所有索引源 $count=$result['total']; //查到的结果条数 $time=$result['time']; //耗时 $arr=$result['matches']; //结果集 $id=''; for($i=0;$i<$count;$i++){ $id.=$arr[$i]['id'].','; }
$id=substr($id,0,-1); //结果集的id字符串
实例三,支持分页的:
<?php header("Content-type: text/html; charset=utf-8"); require("./sphinxapi.php"); $s = new SphinxClient; $s->setServer("192.168.252.132", 9312); //SPH_MATCH_ALL, 匹配所有查询词(默认模式); SPH_MATCH_ANY, 匹配查询词中的任意一个; SPH_MATCH_EXTENDED2, 支持特殊运算符查询 $s->setMatchMode(SPH_MATCH_ALL); $s->setMaxQueryTime(30); //设置最大搜索时间 $s->SetArrayResult(false); //是否将Matches的key用ID代替 $s->SetSelect ( "*" ); //设置返回信息的内容,等同于SQL $s->SetRankingMode(SPH_RANK_BM25); //设置评分模式,SPH_RANK_BM25可能使包含多个词的查询的结果质量下降。 //$s->SetSortMode(SPH_SORT_EXTENDED); //发现增加此参数会使结果不准确 //$s->SetSortMode(SPH_SORT_EXTENDED,"from_id asc,id desc"); //设置匹配项的排序模式, SPH_SORT_EXTENDED按一种类似SQL的方式将列组合起来,升序或降序排列。 $weights = array ('company_name' => 20); $s->SetFieldWeights($weights); //设置字段权重 $s->SetLimits ( 0, 30, 1000, 0 ); //设置结果集偏移量 SetLimits (便宜量,匹配项数目,查询的结果集数默认1000,阀值达到后停止) //$s->SetFilter ( $attribute, $values, $exclude=false ); //设置属性过滤 //$s->SetGroupBy ( $attribute, $func, $groupsort="@group desc" ); //设置分组的属性 $res = $s->query('@* "汽车"','main','--single-0-query--'); #[宝马]关键字,[news]数据源source //代码高亮 $tags = array(); $tags_name = array(); foreach($res['matches'] as $key=>$value){ $tags[] = $value['attrs']; $company_name[] = $value['attrs']['company_name']; $description[] = $value['attrs']['description']; } $company_name = $s->BuildExcerpts ($company_name, 'main', '汽车', $opts=array() ); //执行高亮,这里索引名字千万不能用* $description = $s->BuildExcerpts ($description, 'main', '汽车', $opts=array() ); //执行高亮,这里索引名字千万不能用* foreach($tags as $k=>$v) { $tags[$k]['company_name'] = $company_name[$k]; //高亮后覆盖 $tags[$k]['description'] = $description[$k]; //高亮后覆盖 } // 高亮后覆盖 $i = 0; foreach($res['matches'] as $key=>$value){ $res['matches'][$key] = $tags[$i]; $i++; } $err = $s->GetLastError(); echo '<pre>'; var_export($res); var_export($err); echo '</pre>'; 生成索引时如果出现如下错误: FATAL: failed to lock /usr/local/sphinx/var/data/test1.spl: Resource temporarily unavailable, will not index. Try --rotate option. 请改用命令 ./indexer -c /usr/local/sphinx/etc/sphinx.conf --all --rotate