代码参考自ZF自带的demo。 如下图所示建立工程: ![ZendFramework中使用Lucene全文检索](/uploadfile/201212/7/D0105915827.jpg)
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"; } } } }
(责任编辑:admin) |