搜尋引擎最重要的功能就是查詢資料了,當建立好索引檔後,就可以針對索引檔內容進行查詢,索引資料可分為有做分詞及未做分詞,未做分詞的索引資料,只有全部內容均相同才會找到此筆資料,有做分詞者,則依分詞類型,可能有單字索引,雙字索引或中文字詞索引等,索引做的越好,搜尋到的資料會越精準。
資料Field也分成儲存及不存儲二種,當選擇儲存Store.YES時,查詢到此筆資料時則可以直接取用,不過此方法會佔用較多的空間,不存儲方法Store.NO則相反。
索引資料內容如下:

原始碼如下:
package testlucene;
import java.util.Date;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
public class LuceneSearch {
private IndexSearcher searcher = null;
private Query query = null;
private Analyzer analyzer = new StandardAnalyzer();
public LuceneSearch()
{
try
{
//建立查詢器
searcher = new IndexSearcher(IndexReader.open("d:\\index"));
}
catch(Exception e)
{
}
}
//hits是查詢的結果集
public final Hits search(String keyword)throws Exception
{
System.out.println("正在檢索關鍵字 : "+keyword);
//建立要查詢的("目標",分析器)
QueryParser qp = new QueryParser("contents",analyzer);
//parse(查詢字) ,keyword可以用空白格開,理論上會查出
//A AND B ,A,B 三種結果,放入同一個結果集
//AND OR 大寫是logic判斷用
query = qp.parse(keyword);
Date start = new Date();
//hits是查詢的結果集
Hits hits = searcher.search(query);
Date end = new Date();
System.out.println("檢索完成,用時"+(end.getTime()
-start.getTime())+"毫杪");
return hits;
}
//列印結果集
public void printResult(Hits h)
{
if(h.length()==0)
{
System.out.println("對不起!沒有您要找的資料!");
}
else
{
//hits的length是查到的所有結果
for(int i = 0 ; i <h.length();i++)
{
try
{
//取得第n個查詢結果,此處get("contents")會是null,
//因為content是查詢用欄位
//而get("path")則是敘述欄位
//請在建立index時就定義好
Document doc = h.doc(i);
System.out.println("這是第"+(i+1)+"個檢索到的結果,檔案為 : "
+doc.get("path"));
System.out.println(doc.get("contents"));
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
System.out.println("---------------------------");
}
public static void main(String[] args) throws Exception
{
LuceneSearch test = new LuceneSearch();
test.printResult(test.search("中華"));
test.printResult(test.search("台灣"));
test.printResult(test.search("民國"));
test.printResult(test.search("a.txt"));
}
}
對索引檔進行中華、台灣、民國、a.txt四個字詞的查詢結果如下:

2 thoughts to “apache lucene-建立自己的搜尋引擎-查詢資料”