承接上一篇文章。
package com.amazing; import java.io.File;
import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version; public class HelloLucene { public void search(){
IndexReader reader = null;
IndexSearcher searcher = null;
try {
Directory directory = FSDirectory.open(new File("D:"+File.separator+"lucene"+File.separator+"index01"));
reader = IndexReader.open(directory);
searcher = new IndexSearcher(reader); QueryParser parser = new QueryParser(Version.LUCENE_35,"content",new StandardAnalyzer(Version.LUCENE_35));
Query query = parser.parse("java");
TopDocs tds = searcher.search(query, 10);
ScoreDoc[] sds = tds.scoreDocs;
for(ScoreDoc sd:sds){
Document doc = searcher.doc(sd.doc);
System.out.println(doc.get("filename")+"--->"+doc.get("path"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(searcher != null){
try {
searcher.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} } }
package com.amazing; import org.junit.Test; public class TestLucene { @Test
public void testCreateIndex(){
HelloLucene hl = new HelloLucene();
hl.search();
}
}