Chinaunix首页 | 论坛 | 博客
  • 博客访问: 696638
  • 博文数量: 160
  • 博客积分: 8847
  • 博客等级: 中将
  • 技术积分: 1656
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-25 16:46
个人简介

。。。。。。。。。。。。。。。。。。。。。。

文章分类

全部博文(160)

文章存档

2015年(1)

2013年(1)

2012年(4)

2011年(26)

2010年(14)

2009年(36)

2008年(38)

2007年(39)

2006年(1)

分类: 系统运维

2011-03-21 22:49:18

本文转载地址:http://ythzjk.javaeye.com/blog/333958

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

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

Zend_Search_Lucene 来源于 Apache Lucene project。要了解关于 Lucene 的更多详情,请访问 。

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

首先需下载Zend Framework,下载地址:
我这里用的是Preview 0.1.5版.
具体的使用方法请看官方文档,中文文档在这里:

好,下面请看我的例子。

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

createindex.php

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

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

search.php


  1. <?php
  2. require_once '../includes/application_top.php';
  3. require_once DIR_FS_CATALOG . 'includes/Zend/Search/Lucene.php';
  4. $index = new Zend_Search_Lucene('index');
  5. $str = <<< EOT
  6. <form method=get action="">
  7. <input type="text" name="keywords"><input type="submit">
  8. </form>
  9. EOT;

  10. echo $str;
  11. $keywords = strtolower($_GET['keywords']);
  12. if(! empty($keywords)) {
  13.  $hits = $index->find($keywords);
  14.     echo '
    Search result:
    '
    ;
  15.     foreach ($hits as $hit) {
  16.         echo '. $hit->url . '">' . $hit->title . '
    ';
  17.         echo $hit->contents . '
    '
    ;
  18.     }
  19. }
  20. ?>

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

阅读(741) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~