Zend Search Lucene实现全文搜索收藏

Zend Search Lucene实现全文搜索收藏

新一篇: MySQL的优化  | 旧一篇: 缓存策略的改动

<noscript></noscript>

简介:Zend_Search_Lucene 是一个完全由 PHP 5 编写的通用文本搜索引擎。由于其将索引保存在文件系统中而不需要数据库支持,因此它几乎可以为任何由 PHP 驱动的网站增加搜索能力。Zend_Search_Lucene 支持下列特性:

  • 具有排名功能的搜索——最符合要求的结果出现在最前面
  • 许多强大的查询类型:短语查询、通配符查询、近似查询、范围查询等 
  • 搜索特定的字段,如标题、作者、内容,等等

Zend_Search_Lucene 来源于 Apache Lucene project。要了解关于 Lucene 的更多详情,请访问 http://lucene.apache.org/java/docs/

看了N久,查了许多的文章和例子之后,终于成功运行了,特记录下来,与大家共享。

首先需下载Zend Framework,下载地址:http://framework.zend.com
我这里用的是Preview 0.1.5版.
具体的使用方法请看官方文档,中文文档在这里:http://www.phpeye.com/zf/zend.search.html#zend.search.overview

好,下面请看我的例子。

1、建立索引
你可以对静态页面文件(如新闻网站等)进行索引,也可以对数据库的内容进行索引,总之,一切的数据都
索引。我这里以mysql数据库为例。

createindex.php

<?php
require_once ‘../includes/application_top.php’;
require_once DIR_FS_CATALOG . ‘includes/Zend/Search/Lucene.php’;
if (function_exists(”set_time_limit”) && ! get_cfg_var(’safe_mode’)) {
  set_time_limit(0);
}
$index = new Zend_Search_Lucene(’index’, true);//建立索引对象,TRUE表示一个新的索引
$sql = “SELECT c.categories_name, m.models_id, m.models_name, m.models_series, ” .
         ”m.models_brand, p.products_id, p.products_title…”; //查询数据库产品资料
$result = $class_db->query($sql);
while($row = $result->fetchRow()) {
  $url = ‘http://www.sellcamera.net/detail.php/’ . $row[’products_id’]; //产品链接
  $title = $row[’products_title’];//产品标题
  $description = $models_brand . ‘ ‘ . $models_name . ‘ ‘ . $categories_name; //产品的描述,自己组合它的内容
 // Store document URL to identify it in search result.
  $doc = new Zend_Search_Lucene_Document();//建立一个索引文档
  $doc->addField(Zend_Search_Lucene_Field::UnIndexed(’url’, $url));
  $doc->addField(Zend_Search_Lucene_Field::Text(’title’, $title));
  $doc->addField(Zend_Search_Lucene_Field::Text(’contents’, $description));
  $index->addDocument($doc); //将这个文档加到索引中
}
// Write changes to the index.
$index->commit();//提交,保存索引资料
?>

好的,再运行它,就将网站的所有产品资料的索引保存到指定的目录中了。接下来,我们要做的就是将它们
查找出来。

search.php

<?php
require_once ‘../includes/application_top.php’;
require_once DIR_FS_CATALOG . ‘includes/Zend/Search/Lucene.php’;
$index = new Zend_Search_Lucene(’index’); 
$str = <<< EOT
<form method=get action=”">
<input type=”text” name=”keywords”><input type=”submit”>
</form>
EOT;

echo $str;
$keywords = strtolower($_GET[’keywords’]);
if(! empty($keywords)) {
 $hits = $index->find($keywords);
    echo ‘<br>Search result:<br>’;
    foreach ($hits as $hit) {
        echo ‘<a href=”‘ . $hit->url . ‘”><strong>’ . $hit->title . ‘</strong></a><br>’;
        echo $hit->contents . ‘<hr>’;
    }
}
?>

OK,大功告成,赶快试试吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值