lucene 實現分頁

 1 package com.kite.dispage;  2 
 3 import java.util.ArrayList;  4 import java.util.List;  5 
 6 import org.apache.lucene.document.Document;  7 import org.apache.lucene.index.IndexWriter;  8 import org.apache.lucene.index.IndexWriter.MaxFieldLength;  9 import org.apache.lucene.queryParser.MultiFieldQueryParser; 10 import org.apache.lucene.queryParser.QueryParser; 11 import org.apache.lucene.search.IndexSearcher; 12 import org.apache.lucene.search.Query; 13 import org.apache.lucene.search.ScoreDoc; 14 import org.apache.lucene.search.TopDocs; 15 import org.apache.lucene.util.Version; 16 import org.junit.Test; 17 
18 import com.kite.bean.Article; 19 import com.kite.luncene.utils.DocumentUtils; 20 import com.kite.luncene.utils.LunceneUtils; 21 
22 /**
23  * 分頁 24  * @author admin 25  * 26  */
27 public class DisPageTest 28 { 29  @Test 30     public void testCreateIndexBeath() throws Exception 31  { 32         IndexWriter indexWriter = new IndexWriter(LunceneUtils.directory, LunceneUtils.analyzer, MaxFieldLength.LIMITED); 33         for(int i = 0; i < 1000; i++) 34  { 35             
36             Article article = new Article(); 37             article.setId(1L + i); 38             article.setTitle("luncenes是一個好難寫的東西"); 39             article.setContent("百度,谷歌是很好的搜索引擎"); 40             //經過工具類轉換成document
41             Document document = DocumentUtils.articleToDocument(article); 42  indexWriter.addDocument(document); 43  } 44         
45  indexWriter.close(); 46  } 47     
48     /**
49  * 50  * @param firstResult 51  * 當前頁的第一行在集合中的位置 52  * @param maxResult 53  * 每頁顯示的最大的行數 54  * @throws Exception 55      */
56     public void testSearchIndexDispage(int firstResult,int maxResult) throws Exception 57  { 58         IndexSearcher indexSearcher = new IndexSearcher(LunceneUtils.directory); 59         QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_30, new String[]{"title","content"}, LunceneUtils.analyzer); 60         Query query = queryParser.parse("luncenes"); 61         //查詢的是起點位置到一頁顯示多少行
62         TopDocs topDocs = indexSearcher.search(query,firstResult+maxResult); 63         //返回
64         int count = Math.min(topDocs.totalHits, firstResult+maxResult); 65         ScoreDoc[] scoreDocs = topDocs.scoreDocs; 66         List<Article> articleList = new ArrayList<Article>(); 67         for(int i=firstResult;i<count;i++){ 68             Document document = indexSearcher.doc(scoreDocs[i].doc); 69             Article article = DocumentUtils.documentToArticle(document); 70  articleList.add(article); 71  } 72         
73         for(Article article:articleList){ 74  System.out.println(article.getId()); 75  System.out.println(article.getTitle()); 76  System.out.println(article.getContent()); 77  } 78  } 79     /**
80  * 分頁測試 81      */
82  @Test 83     public void testDisPage() throws Exception 84  { 85         this.testSearchIndexDispage(500,100); 86  } 87 }
相關文章
相關標籤/搜索