您的位置:首页 > 其它

Lucene的分页查询

2012-06-24 21:19 281 查看
  分页查询只需要传入每页显示多少条记录,当前是第几页就可以了。

  当然是对搜索返回的结果进行分页,并不是对搜索结果的总数量进行分页,因为我们搜索的时候都是返回前n条记录。

  例如indexSearcher.search(query, 100);//只返回前100条记录

/**
* 对搜索返回的前n条结果进行分页显示
* @param keyWord 		查询关键词
* @param pageSize		每页显示记录数
* @param currentPage	当前页
* @throws ParseException
* @throws CorruptIndexException
* @throws IOException
*/
public void paginationQuery(String keyWord,int pageSize,int currentPage) throws ParseException, CorruptIndexException, IOException {
String[] fields = {"title","content"};
QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_36,fields,analyzer);
Query query = queryParser.parse(keyWord);

IndexReader indexReader  = IndexReader.open(directory);
IndexSearcher indexSearcher = new IndexSearcher(indexReader);

//TopDocs 搜索返回的结果
TopDocs topDocs = indexSearcher.search(query, 100);//只返回前100条记录
int totalCount = topDocs.totalHits; // 搜索结果总数量
ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 搜索返回的结果集合

//查询起始记录位置
int begin = pageSize * (currentPage - 1) ;
//查询终止记录位置
int end = Math.min(begin + pageSize, scoreDocs.length);

//进行分页查询
for(int i=begin;i<end;i++) {
int docID = scoreDocs[i].doc;
Document doc = indexSearcher.doc(docID);
int id = NumericUtils.prefixCodedToInt(doc.get("id"));
String title = doc.get("title");
System.out.println("id is : "+id);
System.out.println("title is : "+title);
}

}

@Test
public void testPaginationQuery() throws CorruptIndexException, ParseException, IOException{
//每页显示5条记录,显示第三页的记录
paginationQuery("思想",5,3);
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: