R – Zend_Search_Lucene search in array

zend-frameworkzend-search-lucene

Is there a way to store an array as a document field and then query that array?

I've got a collection of items, which are tagged. I'd like to be able to search all items that match for example tags 55 and 67.

How would I achieve this?

Best Solution

First you have to create index file with the data in your array. The documentation covers how to create a new index.

so imagining your array look like

$data = array(
  array(
     'tag' => '55 67',
     'content' => 'Lorem Ipsu 1',
     'url' => 'http://foobar.net/content.php?id=1'
  ),
  array(
     'tag' => '32 67'
     'content' => 'Lorem Ipsu 2',
     'url' => 'http://foobar.net/content.php?id=2'
  )
);

it would give something like that to create your index

 // Create index
$index = Zend_Search_Lucene::create('/data/my-index');


foreach($data as $row){
  $doc = new Zend_Search_Lucene_Document();
  // Store document URL to identify it in the search results
  $doc->addField(Zend_Search_Lucene_Field::Text('url', $row['url']));

  // Store document TAGS 
  $doc->addField(Zend_Search_Lucene_Field::Text('tag', $row['tag']));

  // Index document contents
  $doc->addField(Zend_Search_Lucene_Field::UnStored('contents', $row['content']));

  // Add document to the index
  $index->addDocument($doc);
 }

finally to query your index file

$index = Zend_Search_Lucene::open('/data/my_index');

$hits = $index->find('tag:55 AND tag:67');

foreach ($hits as $hit) {
    echo $hit->score;
    echo $hit->url;
    echo $hit->tag;
}

Note

I am not really sure why you intend to use Lucene to do such work, if you just want a listing of article matching whatever tag would be more easy to do it with plain SQL queries.

After if want to know how Zend_Search_Lucene works that could be an example

Related Question