方法一:将所有的结果搜索出来,再进行分页
public void searchPage(String queryCondition, int pageIndex, int pageSize){ IndexReader indexReader = null; try { Directory directory = FileIndexUtil.getDirectory(); indexReader = IndexReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(indexReader); QueryParser queryParser = new QueryParser(Version.LUCENE_35, "content", new StandardAnalyzer(Version.LUCENE_35)); Query query = queryParser.parse(queryCondition); TopDocs topDocs = indexSearcher.search(query, 100); ScoreDoc[] scoreDocs = topDocs.scoreDocs; int start = (pageIndex - 1) * pageSize; int end = pageIndex * pageSize; if (scoreDocs != null && scoreDocs.length>0){ for (int i = start-1; i < end; i++){ Document document = indexSearcher.doc(scoreDocs[i].doc); System.out.println("filename: "+document.get("filename")+"---->"+" size: "+document.get("size")); } } indexReader.close(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
方法二:利用“searchAfter()”只搜索部分数据,节约资源(注意:3.5之前没有)
/** * 获取上一次搜索最后一项: * 基本思路:将上一次的搜索数量进行限制(条件为最后一项为搜索数量上限),取出最后一项即为上一次搜索的最后一项 * 好处:避免每次都要将所有的索引项搜索出来,浪费资源 */ private ScoreDoc getLastScoreDoc(IndexSearcher indexSearcher, Query query, int pageIndex, int pageSize) throws IOException, ParseException { //若是第一页,就返回null(第一页的前一页没有) if (pageIndex == 1){ return null; } /** * 分析: 1 19 null 2 39 19 */ int num = (pageIndex - 1)*pageSize; TopDocs topDocs = indexSearcher.search(query, num); ScoreDoc[] scoreDocs = topDocs.scoreDocs; return scoreDocs[num-1]; }
/** * 对搜索结果进行分页(第二种方式:只搜索部分数据) */ public void searchPageByAfter(String queryCondition, int pageIndex, int pageSize){ IndexReader indexReader = null; try { Directory directory = FileIndexUtil.getDirectory(); indexReader = IndexReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(indexReader); QueryParser queryParser = new QueryParser(Version.LUCENE_35, "content", new StandardAnalyzer(Version.LUCENE_35)); Query query = queryParser.parse(queryCondition); /** * 获取上一次搜索最后一项 */ ScoreDoc after = getLastScoreDoc(indexSearcher, query, pageIndex, pageSize); /** * 通过上一页的最后一个元素,获取下一页pageSize个元素 * TopDocs searchAfter(ScoreDoc after, Query query, int n) * 参数一:上一次搜索最后一项 * 参数二:查询条件 * 参数三:查询数量 * 优点:避免每次搜索所有,浪费资源 */ TopDocs topDocs = indexSearcher.searchAfter(after, query, pageSize); ScoreDoc[] scoreDocs = topDocs.scoreDocs; int start = (pageIndex - 1) * pageSize; int end = pageIndex * pageSize; if (scoreDocs != null && scoreDocs.length>0){ for (int i = start-1; i < end; i++){ Document document = indexSearcher.doc(scoreDocs[i].doc); System.out.println("filename: "+document.get("filename")+"---->"+" size: "+document.get("size")); } } indexReader.close(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }