添加文件是核心的操作,索引進程的一部分中的一個。
添加包含字段IndexWriter ,IndexWriter用于更新或創(chuàng)建索引文件。
現(xiàn)在,我們將展示一個循序漸進的過程,以得到附加文件的理解,開始使用一個基本的例子。
創(chuàng)建一個方法來獲取從文本文件 Lucene 的文檔
創(chuàng)建各種類型的是含有鍵作為名稱和值作為內(nèi)容被編入索引鍵值對字段
設置字段中進行分析或不設置。在我們的實例中,只有內(nèi)容被分析,因為它可能包含數(shù)據(jù),諸如 a, am, are, an,它不要求在搜索操作等等。
新創(chuàng)建的字段添加到文檔對象并返回給調(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; }
IndexWriter 類作為它在索引過程中創(chuàng)建/更新索引的核心組成部分
創(chuàng)建一個IndexWriter 對象
創(chuà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); }
下面的兩個是添加的文件的方式。
addDocument(Document) - 添加使用默認的分析文檔(在創(chuàng)建索引時,指定寫入器)
addDocument(Document,Analyzer) - 添加使用提供的分析文檔。
private void indexFile(File file) throws IOException{ System.out.println("Indexing "+file.getCanonicalPath()); Document document = getDocument(file); writer.addDocument(document); }
讓我們創(chuàng)建一個測試 Lucene 應用程序來測試索引過程。
步驟 | 描述 |
---|---|
1 | 在包 packagecom.yiibai.lucene 創(chuàng)建一個名稱LuceneFirstApplication項目用作解釋Lucene 也可以使用 EJB 創(chuàng)建的項目 - 第一章申請這樣本章理解索引過程。 |
2 | 創(chuàng)建LuceneConstants.java,TextFileFilter.java和Indexer.java,保持其它的文件不變。 |
3 | 創(chuàng)建 LuceneTester.java 如下所述 |
4 | 清理和構建應用程序,以確保業(yè)務邏輯正在按要求 |
LuceneConstants.java
這個類是用來提供可應用于示例應用程序中使用的各種常量。
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(上一篇:Lucene索引操作下一篇:Lucene WildcardQuery類