August 17, 2014

August 17, 2014
In this article, we are going to discuss about in Zend Framework How to index the content using Zend_Search_Lucene component. Lucene is indexing and retrieval library that originally was developed in Java technology and supported by the Apache Software Foundation. When the data has been indexed in the file system, it does not require a database server. Zend_Search_Lucene is one of the components of the Zend Framework that implements this technology.

Zend_Search_Lucene supports the following features:

  1. Ranking of search results 
  2. Powerful query types: Boolean, wildcard, phrase queries 
  3. Search by specific field

Ok, let's go to the example:

Suppose we have data that we store the article in our index file system. We have a call controller Zend_Search_Lucene components as follows:

class TestluceneController extends Zend_Controller_Action
    public function init()
        /* Initialize action controller here */
        $this->indexPath = APPLICATION_PATH.'/indexsearch/index';

In the init function, we declare the path where we store the index. If so, we created an action to index data from the database, such as the following:

public function reindexAction()
    // action body
    //just SAMPLE , access to db
    // ( in your REAL DEVELOPMENT, access to db is only in model ) !!!!
    //asumption , 'db' is already registered in registry !!!
    $db = Zend_Registry::get('db');
    $fetch = $db->query("select * from articles")->fetchAll();

    $index = Zend_Search_Lucene::create($this->indexPath);

    foreach($fetch as $key=>$row)
        $doc = new Zend_Search_Lucene_Document();
        $doc->addField(Zend_Search_Lucene_Field::Text('title', $row['title']));
        $doc->addField(Zend_Search_Lucene_Field::UnStored('content', $row['content'] ));

        echo 'Added ' . $row['title'] . ' to index.
    //optimize index...


Well, we run the action reindexAction first before attempting to scan the data. If so, now we can test:

//.......Search data is already indexed.
public function searchAction()
    $data  = array();

    // If a search_query parameter has been posted, search the index.
    $indexopen = Zend_Search_Lucene::open($this->indexPath);
     // Get results.
    $data  = $indexopen->find('"PHP framework" AND "Zend Framework"');
    foreach($data as $key=>$row)
        echo $row->title; echo "<br>";


Post a Comment