搜索文檔
利用Lucene進行搜索就像建立索引一樣也是非常方便的。在上面一部分中,我們已經(jīng)為一個目錄下的文本文檔建立好了索引,現(xiàn)在我們就要在這個索引上進行搜索以找到包含某個關鍵詞或短語的文檔。Lucene提供了幾個基礎的類來完成這個過程,它們分別是呢IndexSearcher, Term, Query, TermQuery, Hits. 下面我們分別介紹這幾個類的功能。
Query
這是一個抽象類,他有多個實現(xiàn),比如TermQuery, BooleanQuery, PrefixQuery. 這個類的目的是把用戶輸入的查詢字符串封裝成Lucene能夠識別的Query。
Term
Term是搜索的基本單位,一個Term對象有兩個String類型的域組成。生成一個Term對象可以有如下一條語句來完成:Term term = new Term(“fieldName”,”queryWord”); 其中第一個參數(shù)代表了要在文檔的哪一個Field上進行查找,第二個參數(shù)代表了要查詢的關鍵詞。
TermQuery
TermQuery是抽象類Query的一個子類,它同時也是Lucene支持的最為基本的一個查詢類。生成一個TermQuery對象由如下語句完成: TermQuery termQuery = new TermQuery(new Term(“fieldName”,”queryWord”)); 它的構造函數(shù)只接受一個參數(shù),那就是一個Term對象。
IndexSearcher
IndexSearcher是用來在建立好的索引上進行搜索的。它只能以只讀的方式打開一個索引,所以可以有多個IndexSearcher的實例在一個索引上進行操作。
Hits
Hits是用來保存搜索的結果的。
介紹完這些搜索所必須的類之后,我們就開始在之前所建立的索引上進行搜索了,清單2給出了完成搜索功能所需要的代碼。
清單2 :在建立好的索引上進行搜索
package TestLucene;
import java.io.File;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.FSDirectory;
/**
* This class is used to demonstrate the
* process of searching on an existing
* Lucene index
*
*/
public class TxtFileSearcher {
public static void main(String[] args) throws Exception{
String queryStr = "lucene";
//This is the directory that hosts the Lucene index
File indexDir = new File("D:\\luceneIndex");
FSDirectory directory = FSDirectory.getDirectory(indexDir,false);
IndexSearcher searcher = new IndexSearcher(directory);
if(!indexDir.exists()){
System.out.println("The Lucene index is not exist");
return;
}
Term term = new Term("contents",queryStr.toLowerCase());
TermQuery luceneQuery = new TermQuery(term);
Hits hits = searcher.search(luceneQuery);
for(int i = 0; i < hits.length(); i++){
Document document = hits.doc(i);
System.out.println("File: " + document.get("path"));
}
}
}
|
在清單2中,類IndexSearcher的構造函數(shù)接受一個類型為Directory的對象,Directory是一個抽象類,它目前有兩個子類:FSDirctory和RAMDirectory. 我們的程序中傳入了一個FSDirctory對象作為其參數(shù),代表了一個存儲在磁盤上的索引的位置。構造函數(shù)執(zhí)行完成后,代表了這個IndexSearcher以只讀的方式打開了一個索引。然后我們程序構造了一個Term對象,通過這個Term對象,我們指定了要在文檔的內(nèi)容中搜索包含關鍵詞”lucene”的文檔。接著利用這個Term對象構造出TermQuery對象并把這個TermQuery對象傳入到IndexSearcher的search方法中進行查詢,返回的結果保存在Hits對象中。最后我們用了一個循環(huán)語句把搜索到的文檔的路徑都打印了出來。好了,我們的搜索應用程序已經(jīng)開發(fā)完畢,怎么樣,利用Lucene開發(fā)搜索應用程序是不是很簡單。
|