+ -
当前位置:首页 → 问答吧 → ZendFramework中使用Lucene全文检索

ZendFramework中使用Lucene全文检索

时间:2009-06-24

来源:互联网

代码参考自ZF自带的demo。
如下图所示建立工程:


=700) window.open('http://images.phpfans.net/attach/images/20090624_81a521d62e141035cbccrZxjSa0nuPpw.jpg');" onload="if(this.offsetWidth>'700')this.width='700';if(this.offsetHeight>'700')this.height='700';" >

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\";
      }
    }
  }
}

作者: 淡水   发布时间: 2009-06-24

相关阅读 更多