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.