Field 是最重要的和索引進(jìn)程的基礎(chǔ)單元。它是要索引包含的內(nèi)容的實(shí)際對(duì)象。當(dāng)我們添加一個(gè)字段,Lucene提供使用Field 項(xiàng)字段,其中規(guī)定字段是要搜索的許多控制。
我們添加包含字段IndexWriter,IndexWriter用于更新或創(chuàng)建索引文件。
現(xiàn)在,我們將展示一個(gè)循序漸進(jìn)的過(guò)程,以獲得一個(gè)開(kāi)始在使用基本的例子,在不同 Field 選項(xiàng)的理解。
Index.ANALYZED - 先分析然后做索引。用于普通的文本索引。分析儀將打斷該字段的值轉(zhuǎn)換成標(biāo)記流,每個(gè)令牌是搜索分開(kāi)。
Index.NOT_ANALYZED - 不分析,但這樣做索引。用于完整的文本索引,例如人的名字,URL等。
Index.ANALYZED_NO_NORMS - 變式Index.ANALYZED。分析儀將打破該字段的值轉(zhuǎn)換成標(biāo)記流,每個(gè)令牌是搜索分開(kāi),但規(guī)范是不存儲(chǔ)在indexes.NORMS被用來(lái)提高搜索但有時(shí)內(nèi)存消耗。
Index.Index.NOT_ANALYZED_NO_NORMS - 變式Index.NOT_ANALYZED。索引是這樣做,但規(guī)范NORMS是不存儲(chǔ)在索引。
Index.NO - 字段值不搜索。
創(chuàng)建一個(gè)方法來(lái)從文本獲取Lucene的文檔。
創(chuàng)建各種類型的是含有鍵作為名稱和值作為內(nèi)容被編入索引鍵值對(duì)字段。
設(shè)置字段進(jìn)行分析與否。在這里,只有內(nèi)容是要被分析,因?yàn)樗赡馨瑪?shù)據(jù),諸如,a, am, are, an等它不要求在搜索操作等等。
新創(chuàng)建的字段添加到文檔對(duì)象并返回給調(diào)用者的方法。
private Document getDocument(File file) throws IOException{ Document document = new Document(); //index file contents Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file)); //index file name Field fileNameField = new Field(LuceneConstants.FILE_NAME, file.getName(), Field.Store.YES,Field.Index.NOT_ANALYZED); //index file path Field filePathField = new Field(LuceneConstants.FILE_PATH, file.getCanonicalPath(), Field.Store.YES,Field.Index.NOT_ANALYZED); document.add(contentField); document.add(fileNameField); document.add(filePathField); return document; }
讓我們創(chuàng)建一個(gè)測(cè)試Lucene的應(yīng)用程序來(lái)測(cè)試索引處理。
步驟 | 描述 |
---|---|
1 | 創(chuàng)建一個(gè)LuceneFirstApplication在包packagecom.yiibai.lucene下。也可以使用EJB創(chuàng)建的項(xiàng)目 |
2 | 創(chuàng)建LuceneConstants.java,TextFileFilter.java和Indexer.java。保持其它的文件不變。 |
3 | 創(chuàng)建LuceneTester.java如下所述。 |
4 | 清理和構(gòu)建應(yīng)用程序,以確保業(yè)務(wù)邏輯按要求工作。 |
LuceneConstants.java
這個(gè)類是用來(lái)提供可應(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文件過(guò)濾器。
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
這個(gè)類是用于索引的原始數(shù)據(jù),這樣我們就可以使用Lucene庫(kù),使其可搜索。
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.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache上一篇:Lucene查詢編程下一篇:Lucene搜索操作