import java.io.File; import java.util.Scanner; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; 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.TopScoreDocCollector; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; public class LuceneSearchTest { private static String IndexDir = "D://test//index//"; public static void main(String args[]) { System.out.println("input the keywords"); Scanner cin = new Scanner(System.in); String keywords = cin.next(); try { IndexSearcher is = new IndexSearcher(FSDirectory.open(new File( IndexDir)), true); TopScoreDocCollector c = TopScoreDocCollector.create(100, false); // doc 中没有的,第一个是版本,第二个是field名称,第三个是分析器 QueryParser qp = new QueryParser(Version.LUCENE_CURRENT, "contents", new StandardAnalyzer(Version.LUCENE_CURRENT)); Query q = qp.parse(keywords); is.search(q, c); ScoreDoc[] hits = c.topDocs().scoreDocs; System.out.println(hits.length); for (ScoreDoc s : hits) { // hits中的元素s有个属性doc返回doc的id值,然后, //IndexSearcher有个方法doc(i)返回第i个Document对象, Document d = is.doc(s.doc); System.out.println("find the doc :"+s.doc+" name: "+d.getField("filename")+"the "+s.toString()); } System.out.println("find files total num:"+c.getTotalHits()); } catch (Exception e) { // TODO: handle exception } } } 这个建立的索引是另外一个,是建立的很多文档的一个索引,其中有个函数在3.0的API中没有。