Lucene-adddocument

提供:Dev Guides
移動先:案内検索

Lucene-ドキュメントの追加操作

ドキュメントの追加は、インデックス作成プロセスの中核操作の1つです。

_Field(s)_を含むDocument(s)_を_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);
}

ドキュメントの追加とインデックス作成プロセスの開始

次の2つは、ドキュメントを追加する方法です。

  • * 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アプリケーションテストを作成する必要があります。

Step Description
1 Create a project with a name LuceneFirstApplication under a package com.finddevguides.lucene as explained in the Lucene - First Application chapter. To understand the indexing process, you can also use the project created in EJB - First Application chapter as such for this chapter.
2 Create LuceneConstants.java,TextFileFilter.java and Indexer.java as explained in the Lucene - First Application chapter. Keep the rest of the files unchanged.
3 Create LuceneTester.java as mentioned below.
4 Clean and Build the application to make sure business logic is working as per the requirements.

LuceneConstants.java

このクラスは、サンプルアプリケーション全体で使用されるさまざまな定数を提供するために使用されます。

package com.finddevguides.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.finddevguides.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.finddevguides.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.finddevguides.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。* link:/lucene/data.zip [Test 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

プログラムを正常に実行すると、* indexディレクトリ*に次のコンテンツが表示されます-

Lucene Index Directory