Lucene索引過程


索引過程是Lucene提供的核心功能之一。下圖說明了索引過程和使用的類。IndexWriter是索引過程中最重要的和核心元件。

Indexing Process

新增文件包含欄位IndexWriter,該分析用分析儀分析檔案,然後建立/根據需要並在目錄儲存/更新/開啟/編輯索引。IndexWriter用於更新或建立索引。它不是用來讀取索引。

現在,展示一個循序漸進的過程,以獲得在索引過程的理解,使用一個基本的例子。

建立一個文件

  • 建立一個方法來獲取從文字檔案中獲得 Lucene 的文件。

  • 建立各種型別的是含有鍵作為名稱和值作為內容被編入索引鍵值對欄位。

  • 設定欄位中進行分析或不設定。在我們的範例中,只有內容被分析,因為它可能包含資料,諸如 a, am, are, an,它不要求在搜尋操作等等。

  • 新建立的欄位新增到文件物件並返回給呼叫者的方法。

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

  • IndexWriter 類作為它建立/在索引過程中更新指標的核心組成部分

  • 建立一個 IndexWriter 物件

  • 建立其應指向位置,其中索引是儲存一個lucene的目錄

  • 初始化索引目錄,有標準的分析版本資訊和其他所需/可選引數建立 IndexWriter 物件

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);
}

開始索引過程

private void indexFile(File file) throws IOException{
   System.out.println("Indexing "+file.getCanonicalPath());
   Document document = getDocument(file);
   writer.addDocument(document);
}

應用程式範例

讓我們建立一個測試 Lucene 應用程式來測試索引過程。

步驟 描述
1 在 packagecom.yiibai.lucene 包下建立一個名稱 LuceneFirstApplication 專案用於解釋 Lucene - First Application chapter, 也可以使用 Lucene 的建立專案 -  在 First Application 章這樣本章理解索引過程。
2 建立LuceneConstants.java,TextFileFilter.java和 Indexer.java,其它的檔案儲存不變。
3 建立LuceneTester.java如下所述
4 清理和構建應用程式,以確保業務邏輯按要求

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(".txt");
   }
}

Indexer.java

這個類是用於索引的原始資料,這樣就可以使用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.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class Indexer {

   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);
   }

   public void close() throws CorruptIndexException, IOException{
      writer.close();
   }

   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;
   }   

   private void indexFile(File file) throws IOException{
      System.out.println("Indexing "+file.getCanonicalPath());
      Document document = getDocument(file);
      writer.addDocument(document);
   }

   public int createIndex(String dataDirPath, FileFilter filter) 
      throws IOException{
      //get all files in the data directory
      File[] files = new File(dataDirPath).listFiles();

      for (File file : files) {
         if(!file.isDirectory()
            && !file.isHidden()
            && file.exists()
            && file.canRead()
            && filter.accept(file)
         ){
            indexFile(file);
         }
      }
      return writer.numDocs();
   }
}

LuceneTester.java

這個類是用來測試 Lucene 庫的索引能力。

package com.yiibai.lucene;

import java.io.IOException;

public class LuceneTester {
	
   String indexDir = "E:\Lucene\Index";
   String dataDir = "E:\Lucene\Data";
   Indexer indexer;
   
   public static void main(String[] args) {
      LuceneTester tester;
      try {
         tester = new LuceneTester();
         tester.createIndex();
      } catch (IOException e) {
         e.printStackTrace();
      } 
   }

   private void createIndex() throws IOException{
      indexer = new Indexer(indexDir);
      int numIndexed;
      long startTime = System.currentTimeMillis();	
      numIndexed = indexer.createIndex(dataDir, new TextFileFilter());
      long endTime = System.currentTimeMillis();
      indexer.close();
      System.out.println(numIndexed+" File indexed, time taken: "
         +(endTime-startTime)+" ms");		
   }
}

資料和索引目錄的建立

從 record1.txt 命名檔案 record10.txt 包含簡單的名稱以及學生的其他細節,並把它們放在目錄 E:LuceneData.  索引目錄路徑應建立為 E:LuceneIndex. 執行此程式後,就可以看到該檔案夾中建立的索引檔案的列表。

執行程式:

一旦使用建立源,創造了原始資料,資料目錄和索引目錄來完成,準備好這一步然後編譯和執行程式。要做到這一點,儲存LuceneTester.Java檔案索引標籤中使用Eclipse IDE 執行 Run 選項,或使用Ctrl+ F11來編譯和執行應用程式LuceneTester。如果應用程式一切正常,這將列印在Eclipse IDE的控制台以下訊息:

Indexing E:LuceneDataecord1.txt
Indexing E:LuceneDataecord10.txt
Indexing E:LuceneDataecord2.txt
Indexing E:LuceneDataecord3.txt
Indexing E:LuceneDataecord4.txt
Indexing E:LuceneDataecord5.txt
Indexing E:LuceneDataecord6.txt
Indexing E:LuceneDataecord7.txt
Indexing E:LuceneDataecord8.txt
Indexing E:LuceneDataecord9.txt
10 File indexed, time taken: 109 ms

一旦成功地執行程式,將有以下的索引目錄中的內容:

Lucene Index Directory