public class SearchTest { private static IndexReader reader = null; static { try { reader = DirectoryReader.open( FileIndexUtil.getDirectory() ); } catch (IOException e) { e.printStackTrace(); } } public IndexSearcher getSearcher(){ try { if(reader == null) reader = DirectoryReader.open( FileIndexUtil.getDirectory() ); else { IndexReader tr = DirectoryReader.openIfChanged((DirectoryReader) reader);//这个很重要,防止reader改变后使用新的reader if(tr != null && tr != reader) { reader.close(); reader = tr; } } return new IndexSearcher(reader); } catch (IOException e) { } return null; } public void searchBySort(String queryStr, Sort sort){ try { //1. 通过reader创建IndexSearcher IndexSearcher searcher = getSearcher();//2. 新建一个QueryParser,第一个参数是建立索引中,与new Field()中的第一个参数对应,第二个参数是标准分词器QueryParser queryParser = new QueryParser("content", new StandardAnalyzer());
//3. queryQarse对要搜索的词进行解析
Query query = queryParser.parse(queryStr); TopDocs topDocs = null; if(sort != null) topDocs = searcher.search(query, 4, sort); else topDocs = searcher.search(query, 4); for(ScoreDoc sc : topDocs.scoreDocs) { Document doc = searcher.doc( sc.doc ); System.out.println( doc.get( "name" ) + ":" + doc.get( "path" ) + "---" + doc.get( "size" ) ); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
Lucene5.5对索引进行搜索
最新推荐文章于 2023-05-22 21:35:28 发布