Lucene-deletedocument

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

Lucene-ドキュメントの削除操作

文書の削除は、インデックス作成プロセスのもう1つの重要な操作です。 この操作は、すでにインデックス付けされたコンテンツが更新され、インデックスが無効になるか、インデックスのサイズが非常に大きくなる場合に使用されます。サイズを縮小してインデックスを更新するには、削除操作を実行します。

IndexWriterを使用してインデックスを更新する_Field(s)_を含む_Document(s)_を_IndexWriter_に削除します。

次に、段階的なアプローチを示し、基本的な例を使用してドキュメントを削除する方法を理解できるようにします。

インデックスからドキュメントを削除する

インデックスからドキュメントを削除するには、次の手順に従ってください-

  • ステップ1 *-廃止されたテキストファイルのLuceneドキュメントを削除するメソッドを作成します。
private void deleteDocument(File file) throws IOException {

  //delete indexes for a file
   writer.deleteDocument(new Term(LuceneConstants.FILE_NAME,file.getName()));

   writer.commit();
   System.out.println("index contains deleted files: "+writer.hasDeletions());
   System.out.println("index contains documents: "+writer.maxDoc());
   System.out.println("index contains deleted documents: "+writer.numDoc());
}

IndexWriterを作成する

IndexWriterクラスは、インデックス作成プロセス中にインデックスを作成/更新するコアコンポーネントとして機能します。

IndexWriterを作成するには、次の手順に従ってください-

  • ステップ1 *-IndexWriterのオブジェクトを作成します。
  • ステップ2 *-インデックスを保存する場所を指すLuceneディレクトリを作成します。
  • ステップ3 *-インデックスディレクトリで作成された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);
}

ドキュメントを削除し、インデックス再作成プロセスを開始します

以下は、ドキュメントを削除する方法です。

  • * deleteDocuments(Term)*-その用語を含むすべてのドキュメントを削除します。
  • * deleteDocuments(Term [])*-配列内のいずれかの用語を含むすべてのドキュメントを削除します。
  • * deleteDocuments(Query)*-クエリに一致するすべてのドキュメントを削除します。
  • * deleteDocuments(Query [])*-配列内のクエリに一致するすべてのドキュメントを削除します。
  • deleteAll -すべてのドキュメントを削除します。
private void indexFile(File file) throws IOException {
   System.out.println("Deleting index for "+file.getCanonicalPath());
   deleteDocument(file);
}

応用例

インデックス作成プロセスをテストするために、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. You can also use the project created in EJB - First Application chapter as such for this chapter to understand the indexing process.
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.index.Term;
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 void deleteDocument(File file) throws IOException {
     //delete indexes for a file
      writer.deleteDocuments(
         new Term(LuceneConstants.FILE_NAME,file.getName()));

      writer.commit();
   }

   private void indexFile(File file) throws IOException {
      System.out.println("Deleting index: "+file.getCanonicalPath());
      deleteDocument(file);
   }

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

データおよびインデックスディレクトリの作成

record1.txtからrecord10.txtまでの10個のテキストファイルを使用して、生徒の名前やその他の詳細を含め、E:\ Lucene \ Dataディレクトリに配置しました。 link:/lucene/data.zip [テストデータ]。 インデックスディレクトリパスは、E:\ Lucene \ Indexとして作成する必要があります。 このプログラムを実行すると、そのフォルダーに作成されたインデックスファイルのリストを見ることができます。

プログラムを実行する

ソース、生データ、データディレクトリ、インデックスディレクトリの作成が完了したら、プログラムをコンパイルして実行できます。 これを行うには、 LuceneTester.Java ファイルタブをアクティブのままにして、Eclipse IDEで使用可能な実行オプションを使用するか、 Ctrl + F11 を使用して LuceneTester アプリケーションをコンパイルおよび実行します。 アプリケーションが正常に実行されると、Eclipse IDEのコンソールに次のメッセージが出力されます-

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

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

Lucene Index Directory