GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Friday, April 15, 2011

Zend - Example For Using Lucene

<?php

require_once "Zend/Controller/Action.php";
require_once "Zend/Search/Lucene.php";


class IndexController extends Zend_Controller_Action{

    public function indexAction(){
        $this->_redirect('index/front');
    }


    public function frontAction(){
        $index = new Zend_Search_Lucene('lola', true);
       
        $doc = new Zend_Search_Lucene_Document();
       
        $contents = array(
            'Google is greate one for our company. so when we are ready to make it, please make some time to be user for you',
            'Apple is another sompany for using with some simple of the example for this one.',
            'Microsoft is another one for the coming of the yeras for this one. It has windows',
        );
        $titles = array(
            'Google is technology company mobile',
            'Apple is mobile leader company',
            'Microsoft is king for desktop',
        );
        $links = array(
            'http://google.com',
            'http://apple.com',
            'http://microsoft.com',
        );
       
        for($i=0; $i<count($links); $i++){
            $doc->addField(Zend_Search_Lucene_Field::Keyword('link', $links[$i]));
            $doc->addField(Zend_Search_Lucene_Field::Text('title', $titles[$i]));
            $doc->addField(Zend_Search_Lucene_Field::Unstored('contents', $contents[$i]));
            $index->addDocument($doc);
        }
       
       
        $index->commit();
        echo $index->count()." Documents indexed";

    }
   
   
    public function renderAction(){
   
        $request = $this->getRequest();
        $query = $request->getParam('query');
       
        $index = new Zend_Search_Lucene('lola');
        $hits = $index->find($query);
       
        $output = '<div id="search">';
       
        $output .= '<p>Total Index: '.$index->count().' documents</p>';
        $output .= '<p>Search For: '.$query.' has resulted on '.count($hits).'</p>';
        foreach($hits as $hit){
            $output .= '<div id="item">';
            $output .= '<h2><a href="'.$hit->link.'">'.$hit->title.'</a> '.$hit->score.'</h2>';
            $output .= '</div>';
        }
        $output .= '</div>';
       
        echo $output;
    }   

}

// see more: http://devzone.zend.com/article/91

Share/Bookmark

2 comments: