Question

I am pretty new to programming and definitely to Zend/Lucene indexing. From what I can tell, though, my code is correct. I feel like I may be overlooking a step or something trying to upload changes and adds to the database so that they appear in the search on my website. I'm not getting any kind of an error message though. Below is the code from the controller. I guess let me know if you need anything else to help this make sense. Thanks in advance for any direction you can give.

class SearchController extends Zend_Controller_Action
{

  public function init()
  {
    $auth = Zend_Auth::getInstance();

    if($auth->hasIdentity()) {
      $this->view->identity = $auth->getIdentity(); 
    }
 }

 public function indexAction()
 {
    // action body
 }

 public function buildAction()
 {
    // create the index
    $index = Zend_Search_Lucene::open(APPLICATION_PATH . '/indexes');
    $page = $this->_request->getParam('page');

    // build product pages
     if ($page == 'search') {
       $mdl = new Model_Search();
       $search = $mdl->fetchAll();
       if ($search->count() > 0) {
       foreach ($search as $s) {
         $doc = new Zend_Search_Lucene_Document();
         $doc->addField(Zend_Search_Lucene_Field::unIndexed('id', $s->id));
         $doc->addField(Zend_Search_Lucene_Field::text('name', $s->name));
         $doc->addField(Zend_Search_Lucene_Field::text('uri', $s->uri));
         $doc->addField(Zend_Search_Lucene_Field::text('description', $s->description));
         $index->addDocument($doc);
        }
       }
       $index->optimize();
       $this->view->indexSize = $index->numDocs();
  } 
 }

  public function resultsAction()
  {
    if($this->_request->isPost()) {
    $keywords = $this->_request->getParam('query');
    $query = Zend_Search_Lucene_Search_QueryParser::parse($keywords);
    $index = Zend_Search_Lucene::open(APPLICATION_PATH . '/indexes');
    $hits = $index->find($query);
    $this->view->results = $hits;
    $this->view->keywords = $keywords;
  } else {
    $this->view->results = null;
  }
}

}

Was it helpful?

Solution

Lucene indexes won't stay in sync with your database automatically, you either need to rebuild the entire index or remove and re-add the relevant documents when they change (you cannot edit an existing document).

public function updateAction()
{
   // something made the db change
   $hits = $index->find("name: " . $name);
   foreach($hits as $hit) {
     $index->delete($hit->id)  
   }

   $doc = new Zend_Search_Lucene_Document();
   // build your doc

   $index->add($doc);

}

Note that lucene documents had their own internal id property, and be careful not to mistake it for an id keyword that you provide.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top