更新文檔是另一個重要的操作,它是索引處理的一部分。此操作用于當已經(jīng)索引內(nèi)容被更新和索引變?yōu)闊o效。該操作也被稱為重新編制索引。
我們更新文檔包含IndexWriter字段,IndexWriter用于更新索引。
現(xiàn)在,我們將展示一個循序漸進的過程,以得到更新文檔的理解,開始使用一個基本的例子。
創(chuàng)建更新從更新的文本文件 Lucene 文檔的方法
private void updateDocument(File file) throws IOException{ Document document = new Document(); //update indexes for file contents writer.updateDocument(new Term (LuceneConstants.CONTENTS, new FileReader(file)),document); writer.close(); }
IndexWriter類作為它在索引過程中創(chuàng)建/更新索引的核心組成部分
創(chuàng)建 IndexWriter 對象
創(chuàng)建其應(yīng)指向位置,其中索引是存儲一個lucene的目錄
初始化索引目錄,有標準的分析版本信息和其他所需/可選參數(shù)創(chuàng)建的 IndexWricrter 對象
private IndexWriter writer; public Indexer(String indexDirectoryPath) throws IOException{ //this directory will contain the indexes Directory indexDirectory = FSDirectory.open(new File(indexDirectoryPath)); //create the indexer writer = new IndexWriter(indexDirectory, new StandardAnalyzer(Version.LUCENE_36),true, IndexWriter.MaxFieldLength.UNLIMITED); }
下面的兩個是方式更新文檔。
updateDocument(Term, Document) - 刪除包含該詞條的文檔,并添加使用默認的分析文檔(在創(chuàng)建索引時,指定寫入器)
updateDocument(Term, Document,Analyzer) - 刪除包含該詞條的文檔,并使用提供的分析儀中添加的文件。
private void indexFile(File file) throws IOException{ System.out.println("Updating index for "+file.getCanonicalPath()); updateDocument(file); }
讓我們創(chuàng)建一個測試Lucene的應(yīng)用程序來測試索引處理
| 步驟 | 描述 |
|---|---|
| 1 | 創(chuàng)建一個LuceneFirstApplication在包packagecom.yiibai.lucene下。也可以使用EJB創(chuàng)建的項目 |
| 2 | 創(chuàng)建LuceneConstants.java,TextFileFilter.java和Indexer.java。保持其它的文件不變。 |
| 3 | 創(chuàng)建 LuceneTester.java 如下所述 |
| 4 | 清理和構(gòu)建應(yīng)用程序,以確保按要求處理業(yè)務(wù)邏輯 |
LuceneConstants.java
這個類是用來提供可應(yīng)用于示例應(yīng)用程序中使用的各種常量。
package com.yiibai.lucene; public class LuceneConstants { public static final String CONTENTS="contents"; public static final String FILE_NAME="filename"; public static final String FILE_PATH="filepath"; public static final int MAX_SEARCH = 10; }
TextFileFilter.java
此類用于為.txt文件過濾器
package com.yiibai.lucene; import java.io.File; import java.io.FileFilter; public class TextFileFilter implements FileFilter { @Override public boolean accept(File pathname) { return pathname.getName().toLowerCase().endsWith(".txt"); } }
Indexer.java
這個類是用于索引的原始數(shù)據(jù),這樣我們就可以使用 Lucene 庫,使其可搜索。
package com.yiibai.lucene; import java.io.File; import java.io.FileFilter; import java.io.FileReader; import java.io.IOException; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.上一篇:Lucene環(huán)境設(shè)置下一篇:Lucene分析