Paginating Lucene Search Results
Please read full article from Paginating Lucene Search Results
As we can see in the Lucene FAQ, the Lucene developers recommended approach topagination is re-executing the search and navigating to the correct position in the ScoreDoc array.
As a result, pagination becomes a problem of finding the correct start position and end position in the ScoreDoc array.
Query query = qp.parse(searchTerm);TopDocs hits = searcher.search(query, maxNumberOfResults);ArrayLocation arrayLocation = paginator.calculateArrayLocation(hits.scoreDocs.length, pageNumber, pageSize);for (int i = arrayLocation.getStart() - 1; i < arrayLocation.getEnd(); i++) { int docId = hits.scoreDocs[i].doc; Document doc = searcher.doc(docId); String filename = doc.get("filename"); String contents = doc.get(searchField);}public class Paginator { public ArrayLocation calculateArrayLocation(int totalHits, int pageNumber, int pageSize) { ArrayLocation al = new ArrayLocation(); if (totalHits < 1 || pageNumber < 1 || pageSize < 1) { al.setStart(0); al.setEnd(0); return al; } int start= 1 + (pageNumber -1) * pageSize; int end = Math.min(pageNumber * pageSize, totalHits); if (start > end) { start = Math.max(1, end - pageSize); } al.setStart(start); al.setEnd(end); return al; }}
No comments:
Post a Comment