Lucene實踐之SearchFile

上一篇學習了構建索引,這一篇來檢索索引,一樣是基礎的用法。html

Game Starts

參考文檔java

      1) http://lucene.apache.org/core/4_9_0/demo/src-html/org/apache/lucene/demo/SearchFiles.htmlapache

依賴jar包學習

  上篇Lucene實踐之SearchFile中的jar包便可。spa

主要的類code

  1) IndexReader , 讀取索引文件htm

  2) IndexSearcher , 核心類執行檢索blog

  3) QueryParser , 用於解析用戶查詢詞索引

  4) Analyzer , 分詞器,最好是與構建索引用同樣的文檔

Always Be Coding

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);//分詞器
        //解析查詢,"content"指定了查找的域(Field)
  
27      
QueryParser parser = new QueryParser(Version.LUCENE_46, "content", anlyzer); 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

 TO BE CONTINUED……

相關文章
相關標籤/搜索