Search with Zend_Lucene and Doctrine

SEARCH WITH ZEND_LUCENE AND DOCTRINE

Extends php doctrine record for search with Zend_Lucene

Usage:

1.- Replace base model:

Ex:
replace
abstract class BaseBlacklisted extends Doctrine_Record
with
abstract class BaseBlacklisted extends SRecord//Doctrine_Record

2.- search in controller

$filename = '/search/indexfile';
$index = Zend_Search_Lucene::open($filename);
Zend_Search_Lucene::setResultSetLimit(300);
$query = '*'.$query.'*';
$results = $index->find($query);

 

Code

abstract class SRecord extends Doctrine_Record {
	private function getIndex() {
		//create or load index
		$filename = '/search/indexfile';
		try {
			if (file_exists($filename)) {
				return Zend_Search_Lucene::open($filename);
			} else {
				return Zend_Search_Lucene::create($filename);
			}
		} catch (Zend_Exception $e) {
			return Zend_Search_Lucene::create($filename);
		}
	}
	private function deletePrevious() {
		$index = $this->getIndex();
		$t = $this->getTable();
		$key = $this->get($t->getIdentifier()) . $t->name;
		$term = new Zend_Search_Lucene_Index_Term($key, 'key');
		$hits = new Zend_Search_Lucene_Search_Query_Term($term);
		foreach ($hits as $hit) {
			if ($hit->key == $key) {
				$index->delete($hit->id);
			}
		}
		$index->commit();
	}
	public function postInsert(Doctrine_Event $event) {
		try {
			$index = $this->getIndex();
			$doc = new Zend_Search_Lucene_Document();
			$t = $this->getTable();
			$colinfo = $t->getColumns();
			$doc->addField(Zend_Search_Lucene_Field::UnIndexed('table', $t->name));
			$doc->addField(Zend_Search_Lucene_Field::UnIndexed('idtable', $this->get($t->getIdentifier())));
			foreach ($colinfo as $colname=>$value) {
		    		$doc->addField(Zend_Search_Lucene_Field::Text($colname, $this->get($colname)));
			}
			$doc->addField(Zend_Search_Lucene_Field::Text('key', $this->get($t->getIdentifier()).$t->name));
			$index->addDocument($doc);
			$index->commit();
		} catch (Zend_Exception $e) {
			echo $e;
		}
	}
	public function postUpdate(Doctrine_Event $event) {
		try {
			$this->deletePrevious();
			$index = $this->getIndex();
			$doc = new Zend_Search_Lucene_Document();
			$t = $this->getTable();
			$colinfo = $t->getColumns();
			$doc->addField(Zend_Search_Lucene_Field::UnIndexed('table', $t->name));
			$doc->addField(Zend_Search_Lucene_Field::UnIndexed('idtable', $this->get($t->getIdentifier())));
			foreach ($colinfo as $colname=>$value) {
		    		$doc->addField(Zend_Search_Lucene_Field::Text($colname, $this->get($colname)));
			}
	    		$doc->addField(Zend_Search_Lucene_Field::Text('key', $this->get($t->getIdentifier()).$t->name));
			$index->addDocument($doc);
			$index->commit();
		} catch (Zend_Exception $e) {
			echo $e;
		}
	}
	public function postDelete(Doctrine_Event $event) {
		try {
			$this->deletePrevious();
		} catch (Zend_Exception $e) {
			echo $e;
		}
	}
}
By Efra, published on October 31, 2010
Comment
*User:
Email:
Url:
*Comment:
  * Required fields
 
 
RSS RSS RSS