Paginating Zend_Search_Lucene results

This short entry was inspired by a snippet of inefficient code I encountered, which involved iterating over an array with a loop and breaking out of it once enough results were fetched.

Zend_Search_Lucene does not paginate results. It simply returns an array. While it does allow you to specify to only return the first N results (using Zend_Search_Lucene::setResultSetLimit($limit)), this is not really all too useful.

$lucene = Zend_Search_Lucene::open('index');
$hits = $lucene->find('author:"mark twain"');
$page = 1;
$perpage = 10;
return array_slice($hits, $page * $perpage - $perpage, $perpage);

The key element here, of course, is the use of array_slice(), which can be used with any array. So this isn't specific to Zend_Search_Lucene in any way.

This entry was posted in Development, PHP, Zend Framework and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>