【摘 要】Lucene 是一個基于 Java 的全文信息檢索工具包,它不是一個完整的搜索應用程序,而是為你的應用程序提供索引和搜索功能。Lucene 目前是 Apache Jakarta 家族中的一個開源項目。也是目前最為流行的基于 Java 開源全文檢索工具包。
【關鍵詞】搜索引擎;Lucene;全文搜索
中圖分類號:TP18 文獻標識碼:A 文章編號:1009-8283(2009)03-0107-01
這是一個建立文件索引的例子
public void doIndex () throws IOException
{
Date date1 = new Date();?
IndexWriter writer = new IndexWriter(\"c:\\\\\\\\index\",new StandardAnalyzer(),true);
File file = new File(\"c:\\\\\\\\file\");
/**
* 例子主要是將C:\\\\\\\\file目錄下的文件的內(nèi)容進行建立索引,將文件路徑作為搜索內(nèi)容的附屬.
*/
if(file.isDirectory())
{
String[]fileList = file.list();
for (int i = 0;i < fileList.length;i++)
{
Document doc = new Document();
File f = new File(file,
fileList[i]);
Reader reader = new BufferedReader(new FileReader(f));
doc.add(new Field(\"file\",reader));//為doument添加field
doc.add(new Field(\"path\",f.getAbsolutePath(),F(xiàn)ield.Store.YES,F(xiàn)ield.Index.NO));
writer.addDocument(doc);
}
}
writer.close();//這一步是必須的,只有這樣數(shù)據(jù)才會被寫入索引的目錄里
Date date2 = new Date();
System.out.println(\"用時\"+(date2.getTime()-date1.getTime())+\"毫秒\");
}
分析
為了對文檔進行索引,Lucene 提供了五個基礎的類,他們分別是 Document,F(xiàn)ield,IndexWriter,Analyzer,Directory。下面我們分別介紹一下這五個類的用途:
Document
Document 是用來描述文檔的,這里的文檔可以指一個 HTML 頁面,一封電子郵件,或者是一個文本文件。一個 Document 對象由多個 Field 對象組成的。可以把一個 Document 對象想象成數(shù)據(jù)庫中的一個記錄,而每個 Field 對象就是記錄的一個字段。
Field
Field 對象是用來描述一個文檔的某個屬性的,比如一封電子郵件的標題和內(nèi)容可以用兩個 Field 對象分別描述。
Analyzer
在一個文檔被索引之前,首先需要對文檔內(nèi)容進行分詞處理,這部分工作就是由 Analyzer 來做的。Analyzer 類是一個抽象類,它有多個實現(xiàn)。針對不同的語言和應用需要選擇適合的 Analyzer。Analyzer 把分詞后的內(nèi)容交給 IndexWriter 來建立索引。
IndexWriter
IndexWriter 是 Lucene 用來創(chuàng)建索引的一個核心的類,他的作用是把一個個的 Document 對象加到索引中來。
Directory
這個類代表了 Lucene 的索引的存儲的位置,這是一個抽象類,它目前有兩個實現(xiàn),第一個是 FSDirectory,它表示一個存儲在文件系統(tǒng)中的索引的位置。第二個是 RAMDirectory,它表示一個存儲在內(nèi)存當中的索引的位置。
其實從上面的例子就可以看出建立索引就用到Document,IndexWriter,F(xiàn)ield。
最簡單的步驟就是:
首先分別new 一個Document,IndexWriter,F(xiàn)ield
然后用Doument.add()方法加入Field,
其次用IndexWrtier.addDocument()方法加入Document。
最后調(diào)用一下IndexWriter.close()方法關閉輸入索引,這一步非常的重要只有調(diào)用這個方法索引才會被寫入索引的目錄里,而這是被很多初學的人所忽略的。
一個通過索引來全文檢索的例子
public void doSearch() throws IOException,ParseException
{
IndexSearcher indexSearcher = new IndexSearcher(\"c:\\\\\\\\index\");
QueryParser queryParser = new QueryParser(\"file\",//這是一個分詞器
new StandardAnalyzer());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Query query = queryParser.parse(br.readLine());
Hits hits = indexSearcher.search(query);
Document doc = 1;
System.out.print(\"正搜索................\");
for (int i = 0;i < hits.length();i++)
{
doc = hits.doc(i);
System.out.println(\"內(nèi)容是:\"+doc.get(\"file\"));
System.out.println(\"文件的路徑是:\" + doc.get(\"path\"));
}
}
利用Lucene進行搜索就像建立索引一樣也是非常方便的。在上面一部分中,我們已經(jīng)為一個目錄下的文本文檔建立好了索引,現(xiàn)在我們就要在這個索引上進行搜索以找到包含某個關鍵詞或短語的文檔。