上一篇学习了构建索引,这一篇来检索索引,同样是基础的用法。
参考文档
1) http://lucene.apache.org/core/4_9_0/demo/src-html/org/apache/lucene/demo/SearchFiles.html
依赖jar包
上篇Lucene实践之SearchFile中的jar包即可。
主要的类
1) IndexReader , 读取索引文件
2) IndexSearcher , 核心类执行检索
3) QueryParser , 用于解析用户查询词
4) Analyzer , 分词器,最好是与构建索引用一样的
searchFile
1 package lucene; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 import org.apache.lucene.analysis.Analyzer; 7 import org.apache.lucene.analysis.standard.StandardAnalyzer; 8 import org.apache.lucene.document.Document; 9 import org.apache.lucene.index.DirectoryReader; 10 import org.apache.lucene.index.IndexReader; 11 import org.apache.lucene.queryparser.classic.ParseException; 12 import org.apache.lucene.queryparser.classic.QueryParser; 13 import org.apache.lucene.search.IndexSearcher; 14 import org.apache.lucene.search.Query; 15 import org.apache.lucene.search.ScoreDoc; 16 import org.apache.lucene.search.TopDocs; 17 import org.apache.lucene.store.FSDirectory; 18 import org.apache.lucene.util.Version; 19 20 public class Searcher { 21 public static IndexSearcher indexSearcher; 22 public static void search(String index,String queryStr) throws IOException, ParseException { 23 long start = System.currentTimeMillis(); 24 IndexReader indexReader = DirectoryReader.open(FSDirectory.open(new File(index)));//读取索引 25 indexSearcher = new IndexSearcher(indexReader); 26 Analyzer anlyzer = new StandardAnalyzer(Version.LUCENE_46);//分词器 27 QueryParser parser = new QueryParser(Version.LUCENE_46, "content", anlyzer);//解析查询,"content"指定了查找的域(Field) 28 Query query = parser.parse(queryStr); 29 TopDocs results = indexSearcher.search(query, 10);//返回10条结果 30 ScoreDoc[] hits = results.scoreDocs; 31 int totalHits = results.totalHits; 32 for(int i = 0; i < totalHits; i++) { 33 Document doc = indexSearcher.doc(hits[i].doc); 34 System.out.println("["+doc.get("name")+"] " + doc.get("path")); 35 System.out.println(); 36 } 37 long end = System.currentTimeMillis(); 38 System.out.println("共找到"+totalHits+"条结果,耗时:"+(end-start)+"ms"); 39 } 40 public static void main(String[] args) throws IOException, ParseException { 41 search("E:/data/index", "never"); 42 } 43 }
结果显示
[nevergrowold.txt] E:\data\data2\nevergrowold.txt
共找到1条结果,耗时:143ms
Lucene实践之SearchFile,布布扣,bubuko.com
原文:http://www.cnblogs.com/erbin/p/3923198.html