`
ythzjk
  • 浏览: 74517 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论

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,大功告成,赶快试试吧。

分享到:
评论
1 楼 kingheaven 2009-07-30  
我试了这个类库, 它不知道lucene2.4生成的数据.

相关推荐

Global site tag (gtag.js) - Google Analytics