/**
* 搜索
*/
public void searcher(){
IndexReader reader = null;
try {
//1.创建Directory
Directory directory = FSDirectory.open(new File("D:/Lucene/index01"));//索引是建立在硬盘上
//2.创建IndexReader
reader = IndexReader.open(directory);
//3.根据IndexReader创建IndexSearcher
IndexSearcher searcher = new IndexSearcher(reader);
//4.创建搜索的Query
//创建Parser来确定要搜索文件的内容,第二个参数表示搜索的域
QueryParser parser = new QueryParser(Version.LUCENE_36,"content",new StandardAnalyzer(Version.LUCENE_36));
//创建Query表示搜索域为content中包含Thread的文档
Query query = parser.parse("wuchaowen");
//5.根据Seracher搜索并返回TopDocs
TopDocs tds = searcher.search(query, 10);//搜索的条数
//6.根据TopDocs获取ScoreDoc对象
ScoreDoc[] sds = tds.scoreDocs;
for(ScoreDoc sd:sds){
//7.根据Searcher和ScoreDoc对象获取Document对象
Document doc = searcher.doc(sd.doc);
//8.根据Document对象获取需要的值
System.out.println(doc.get("filename")+"["+doc.get("path")+"]");
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}finally{
//9.关闭Reader
if(reader!=null)
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
源码