sphinx 安装完成之后
1、生成主数据索引
cd /usr/local/coreseek/bin./indexer ind_main
2、启动 searchd 进程,为php 程序连接准备
./searchd
接下来的事情就交给php了,在压缩包里面有个 sphinxapi.php 调用之
<?php
header("Content-Type:text/html;charset=utf-8");
$keywords = $_GET['keywords'];
//分页
$p = $_GET['p'];
//先在linux中启动sphinx: /usr/local/coreseek/bin/searchd
//1.连sphinx(通过sphinx的api)
//2.调用sphinx的方法得到文档ID,权重等信息
//3.通过文档ID,去MySQL的p表中,查对应数据
//4.对返回结果加工处理(关键字红色)
include './sphinxapi.php';
$limit = 10;
if( $p ){
$start = ($p-1)*$limit+1;
}else {
$start = 0;
}
$sp = new SphinxClient();
//百度-日语 包含百度 ,不包含日语的结果
$sp->setServer('localhost', 9312);
//设置权重值的范围
$sp->setWeights(array(100,1));
$sp->setLimits( $start , $limit );
$sp->SetMatchMode ( SPH_MATCH_EXTENDED2 );//设置模式
$sp->SetRankingMode ( SPH_RANK_PROXIMITY );//设置评分模式
$sp->SetFieldWeights (array('title'=>2,'content'=>1));//设置字段的权重,如果area命中,那么权重算2
$sp->SetSortMode (SPH_SORT_EXTENDED,'@weight DESC');//
$result = $sp->query($keywords, 'ind_main');//第二个参数是索引名
echo '<pre> 总共找到 文档数';
var_dump( $result['total'] );
echo '<pre> 搜索用时';
var_dump( $result['time'] );
if($result['total']==0){
die('暂无数据');
}
$ids = join(',', array_keys($result['matches']));
//echo $ids;//1,2,4,5,6,7,8,12,14
$sql = 'SELECT id,title,content, url FROM crawl_contents WHERE id IN ('. $ids . ') ORDER BY field(id,' .$ids . ')';
//echo $sql;
$lind = mysql_connect('localhost', 'root', 'liuhan');
mysql_set_charset('UTF8');
mysql_select_db('test');
$res = mysql_query($sql);
$posts = array();
$weight = array();
if($res!== false && mysql_num_rows($res)>0){
while($row = mysql_fetch_assoc($res)){
$posts[] = $row;
$id = $row['id'];
$weight[$id] = $result['matches'][$id]['weight'];
}
}
//var_dump( $posts );die();
//对结果加颜色
$options = array(
'before_match'=>'<span style="color:red">',
'after_match'=>'</span>',
);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h3>查询结果</h3>
<table>
<tr>
<td>id</td>
<td>weight</td>
<td>职位名称</td>
<td>职位详情</td>
<td>链接</td>
</tr>
<?php foreach($posts as $item){
$url = $item['url'];
unset( $item['url'] ); //去除链接,不做高亮
$row = $sp->buildExcerpts($item, 'ind_main', $keywords, $options);
$row['url'] = $url;
//var_dump($row);exit;
//注意 $row是索引数组
?>
<tr>
<td><?php echo $item['id'];?></td>
<td><?php echo $weight[$item['id']] ;?></td>
<td><?php echo $row[1];?></td>
<td><?php echo $row[2];?></td>
<td><?php echo "<a target='_blank' href='".$row['url']."'> ".$row['url']."</a>";?></td>
</tr>
<?php } ?>
</table>
</body>
</html>