Lucene - 新增文件操作



新增文件是索引過程的核心操作之一。

我們將包含欄位文件新增到IndexWriter中,其中IndexWriter用於更新或建立索引。

我們現在將向您展示一個分步方法,並幫助您瞭解如何使用基本示例新增文件。

向索引新增文件

請按照以下步驟向索引新增文件:

步驟 1 - 建立一個方法,從文字檔案獲取 Lucene 文件。

步驟 2 - 建立各種欄位,這些欄位是鍵值對,其中鍵為名稱,值為要索引的內容。

步驟 3 - 設定欄位是否要進行分析。在我們的例子中,只有內容需要進行分析,因為它可能包含諸如 a、am、are、an 等資料,這些資料在搜尋操作中不需要。

步驟 4 - 將新建立的欄位新增到文件物件中,並將其返回給呼叫方法。

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:

步驟 1 - 建立 IndexWriter 物件。

步驟 2 - 建立一個 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);
}

新增文件並開始索引過程

以下兩種方法可以新增文件。

  • addDocument(Document) - 使用預設分析器(在建立索引編寫器時指定)新增文件。

  • addDocument(Document,Analyzer) - 使用提供的分析器新增文件。

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

示例應用程式

要測試索引過程,我們需要建立 Lucene 應用程式測試。

步驟 描述
1 在包 com.tutorialspoint.lucene 下建立一個名為 LuceneFirstApplication 的專案,如Lucene - 第一個應用程式章節中所述。為了理解索引過程,您也可以使用在EJB - 第一個應用程式章節中建立的專案,在本節中使用該專案。
2 建立 LuceneConstants.java,TextFileFilter.javaIndexer.java,如Lucene - 第一個應用程式章節中所述。保持其餘檔案不變。
3 建立 LuceneTester.java,如下所示。
4 清理並構建應用程式,以確保業務邏輯按要求工作。

LuceneConstants.java

此類用於提供可在整個示例應用程式中使用的各種常量。

package com.tutorialspoint.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.tutorialspoint.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.tutorialspoint.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.tutorialspoint.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 的 10 個文字檔案,其中包含學生姓名和其他詳細資訊,並將它們放在 E:\Lucene\Data 目錄中。 測試資料。應建立索引目錄路徑為 E:\Lucene\Index。執行此程式後,您可以在該資料夾中看到建立的索引檔案列表。

執行程式

完成原始碼建立、原始資料建立、資料目錄和索引目錄建立後,您就可以準備進行此步驟,即編譯和執行您的程式。為此,請保持 LuceneTester.Java 檔案選項卡處於活動狀態,並使用 Eclipse IDE 中提供的“執行”選項,或使用 Ctrl + F11 編譯並執行您的 LuceneTester 應用程式。如果您的應用程式成功執行,它將在 Eclipse IDE 的控制檯中列印以下訊息:

Indexing E:\Lucene\Data\record1.txt
Indexing E:\Lucene\Data\record10.txt
Indexing E:\Lucene\Data\record2.txt
Indexing E:\Lucene\Data\record3.txt
Indexing E:\Lucene\Data\record4.txt
Indexing E:\Lucene\Data\record5.txt
Indexing E:\Lucene\Data\record6.txt
Indexing E:\Lucene\Data\record7.txt
Indexing E:\Lucene\Data\record8.txt
Indexing E:\Lucene\Data\record9.txt
10 File indexed, time taken: 109 ms

成功執行程式後,您的 索引目錄 中將包含以下內容:

Lucene Index Directory
lucene_indexing_operations.htm
廣告

© . All rights reserved.