ZendFramework中使用Lucene全文检索


代码参考自ZF自带的demo。

  如下图所示建立工程:

  library下建立lucene的模块。

  FileDocument.php:

<?php
require_once'Zend/Search/Lucene.php';
classFileDocumentextendsZend_Search_Lucene_Document
{
  publicfunction__construct($fileName,$storeContent=false)
  {
    if(!file_exists($fileName)){
      thrownewZend_Search_Lucene_Exception("Filedoesn'texists.Filename:'$fileName'");
    }
    $this->addField(Zend_Search_Lucene_Field::Text('path',$fileName));
    $this->addField(Zend_Search_Lucene_Field::Keyword('modified',filemtime($fileName)));
    $f=fopen($fileName,'rb');
    $byteCount=filesize($fileName);
    $data='';
    while($byteCount>0&&($nextBlock=fread($f,$byteCount))!=false){
      $data.=$nextBlock;
      $byteCount-=strlen($nextBlock);
    }
    fclose($f);
    if($storeContent){
      $this->addField(Zend_Search_Lucene_Field::Text('contents',$data,'ISO8859-1'));
    }else{
      $this->addField(Zend_Search_Lucene_Field::UnStored('contents',$data,'ISO8859-1'));
    }
  }
}
?>

  测试代码如下:

<?php
require_once'Zend/Controller/Action.php';
require_once'Lucene/FileDocument.php';
classIndexControllerextendsZend_Controller_Action 
{
  publicfunctioninit()
  {
    $index=newZend_Search_Lucene('index',true);
    setlocale(LC_CTYPE,'en_US');
    $indexSourceDir='C:/IndexSource';
    $dir=opendir($indexSourceDir);
    while(($file=readdir($dir))!==false){
      if(is_dir($indexSourceDir.'/'.$file)){
        continue;
      }
      if(strcasecmp(substr($file,strlen($file)-5),'.html')!=0){
        continue;
      }
      //CreatenewDocumentfromafile
      $doc=newFileDocument($indexSourceDir.'/'.$file,true);
      //Adddocumenttotheindex
      $index->addDocument($doc);
      echo$file."...n";
      flush();
    }
    closedir($dir);
  }
  publicfunctionindexAction() 
  {
    $index=newZend_Search_Lucene('index');
    echo"Indexcontains{$index->count()}documents.n";
    $search='explanations';
    $hits =$index->find(strtolower($search));
    echo"Searchfor"$search"returned".count($hits)."hits.nn";
    foreach($hitsas$hit){
      echostr_repeat('-',80)."n";
      echo'ID:  '.$hit->id          ."n";
      echo'Score:'.sprintf('%.2f',$hit->score)."nn";
      foreach($hit->getDocument()->getFieldNames()as$field){
        echo"$field:n";
        echo'  '.trim(substr($hit->$field,0,76))."n";
      }
    }
  }
}



相关阅读:
js获取单元格自定义属性值的代码(IE/Firefox)
WordPress安装插件内存不足的解决
js 页面刷新location.reload和location.replace的区别小结
HTML5的结构和语义(2):结构
JavaScript几种形式的树结构菜单
line-height属性的继承问题
译文:CSS transitions#CSS3变换入门
sqlserver 中charindex/patindex/like 的比较
继续收藏一些PHP常用函数
DW中链接mysql数据库时,建立字符集中文出现乱码的解决方法
linux AS3 oracle9i 安装指南
Linux系统各版本的本地root密码破解方法
微软称:发现DirectX安全漏洞但Windows 7不受影响
图解MySQL数据库的安装和操作
快速导航

Copyright © 2016 phpStudy |