您的位置:首页 > 其它

lucene-分页

2018-01-29 22:40 85 查看
分页也是通过查询来搞
修改findIndex方法


//int firstResult,int maxResult都是分页所需要的参数

//firstResult:从哪条数据开始

//maxResult:最多取几条
public void findIndex
(String keywords,int firstResult,int maxResult) throws Exception{
IndexSearcher indexSearcher = LuceneUtils.getIndexSearcher();
String fields[] = {"title","content"};
QueryParser queryParser = new MultiFieldQueryParser(LuceneUtils.getVersion(),fields,LuceneUtils.getAnalyzer());
Query query = queryParser.parse(keywords);
 
 //分页开始
//使用lucene提供的api进行操作...
TopDocs topDocs = indexSearcher.search(query, firstResult + maxResult);
ScoreDoc scoreDocs[] = topDocs.scoreDocs;
 
 //判断:scoerDocs的length(实际取出来的数量..)与firstResult + maxResult的取值
int endResult = Math.min(scoreDocs.length, firstResult + maxResult);
for (int i = firstResult; i < endResult; i++) {
int docID = scoreDocs[i].doc;

4000
Document document = indexSearcher.doc(docID);
System.out.println("id===" + document.get("id"));
System.out.println("title===" + document.get("title"));
System.out.println("content===" + document.get("content"));
System.out.println("url===" + document.get("url"));
System.out.println("author===" + document.get("author"));
}

}
OK,测试
首先往Lucene里存点数据

@Test

public void testCreate() throws IOException{
for (int i = 1; i <= 25; i++) {
Article article = new Article();
article.setId(i);
article.setTitle("一定要有梦想,万一实现了呢");
article.setContent("这句话太矫情了");
article.setUrl("http://www.tianmao.com");
article.setAuthor("马云");
luceneDao.addIndex(article);
}

}
注意,这样存的话可能会报错,要将LuceneUtils的一个方面改成这样。因为原来是有一个为空判断的。只有当数据库为空的时候才会插入数据。在我们插入多条数据时,插入过一条,再插入第二条数据库就不再为空,也就导致了插入失败。所以插入数据的时候,要将这个为空判断改掉;

/**

* @return 返回用于操作索引的对象...

* @throws IOException

*/

public static IndexWriter getIndexWriter() throws IOException{
indexWriter = new IndexWriter(directory,indexWriterConfig);
return indexWriter;

}
插入数据完毕之后,可以测试,从第0条数据开始,取5条:

@Test

public void testSearcher() throws Exception{
//limit(0,10)
//从20开始,取10条
luceneDao.findIndex("梦想",0,5);

}
查询带有"梦想"的数据:
 



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