coreseek实战(三):全文搜索在php中应用(使用api接口)

这一篇文章开始学习在php页面中通过api接口,使用coreseek全文搜索。

第一步:综合一下前两篇文章,coreseek实战(1)中的数据源换成实战(2)中的 mysql 数据源配置。然后创建索引文件:

D:\www\coreseek>bin\indexer -c etc\csft_mysql.conf dede
Coreseek Fulltext 3.2 [ Sphinx 0.9.9-release (r2117)]
Copyright (c) 2007-2011,
Beijing Choice Software Technologies Inc (http://www.coreseek.com)

 using config file 'etc\csft_mysql.conf'...
indexing index 'dede'...
collected 354 docs, 2.2 MB
sorted 0.5 Mhits, 100.0% done
total 354 docs, 2207983 bytes
total 2.117 sec, 1042951 bytes/sec, 167.21 docs/sec
total 2 reads, 0.002 sec, 748.5 kb/call avg, 1.2 msec/call avg
total 9 writes, 0.008 sec, 396.2 kb/call avg, 0.9 msec/call avg

第二步:安装并开启 searchd 服务

在coreseek实战(一)中,有一部分错误的,但已经原文修正,具体见实战(一)第一步的第5点。

第二步:coreseek php api接口的使用

在coreseek/api目录下,有个名为 sphinxapi.php 的文件,这就是php api接口。我们复制一份到网站根目录下(我这里是http://localhost/php/),同时在该目录下创建index.php文档,呆会我们通过该页面来实现查询功能。

index.php 页面代码:

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>coreseek中文全文搜索在php程序中的应用</title>
</head>
<body>
<h3><font color="blue">coreseek全文搜索在php程序中应用</font></h3>
<form action="index.php" method="post">
输入搜索的关键词:<input type="text" name="keyword" size="30" />
<input type="submit" name="sub" value="搜索" />
</form>
<hr />
<?php
echo "<pre />";
#引入接口文件,其实你懂的,就是一个类
require_once('sphinxapi.php');
if(isset($_POST['sub']) && $_POST['keyword'] != ''){
    $keyword = trim($_POST['keyword']);    //接收关键词

    $sph = new SphinxClient();            //实例化 sphinx 对象
    $sph->SetServer('localhost',9312);    //连接9312端口
    $sph->SetMatchMode(SPH_MATCH_ANY);    //设置匹配方式
    $sph->SetSortMode(SPH_SORT_RELEVANCE);    //查询结果根据相似度排序
    $sph->SetArrayResult(true);                //设置结果返回格式,true以数组,false以PHP hash格式返回,默认为false
    
    $result = $sph->query($keyword, 'dede');//执行搜索操作,参数(关键词,索引名)
    print_r($result);
}
?>

结果返回一个数组,注意观察一下,数组中有一个键名为[matches]单元,这就是匹配的结果,我们需要获取[matches]下的键名,即是文档的id。然后再根据 id 来查找数据库,获取到匹配结果里对应的文章即可,详细代码见下一篇文章。

posted @ 2013-02-07 00:39  php之路  阅读(1753)  评论(0编辑  收藏  举报