Lucene-quick-guide

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

Lucene-概要

Luceneは、シンプルでありながら強力なJavaベースの Search ライブラリです。 任意のアプリケーションで使用して、検索機能を追加できます。 Luceneはオープンソースプロジェクトです。 スケーラブルです。 この高性能ライブラリは、実質的にあらゆる種類のテキストのインデックス作成と検索に使用されます。 Luceneライブラリは、検索アプリケーションで必要なコア操作を提供します。 インデックス作成と検索。

検索アプリケーションの仕組み

検索アプリケーションは、次の操作のすべてまたはいくつかを実行します-

Step Title Description
1 Acquire Raw Content The first step of any search application is to collect the target contents on which search application is to be conducted.
2 Build the document The next step is to build the document(s) from the raw content, which the search application can understand and interpret easily.
3 Analyze the document Before the indexing process starts, the document is to be analyzed as to which part of the text is a candidate to be indexed. This process is where the document is analyzed.
4 Indexing the document Once documents are built and analyzed, the next step is to index them so that this document can be retrieved based on certain keys instead of the entire content of the document. Indexing process is similar to indexes at the end of a book where common words are shown with their page numbers so that these words can be tracked quickly instead of searching the complete book.
5 *User Interface for Search * Once a database of indexes is ready then the application can make any search. To facilitate a user to make a search, the application must provide a user* a mean or a user interface* where a user can enter text and start the search process.
6 Build Query Once a user makes a request to search a text, the application should prepare a Query object using that text which can be used to inquire index database to get the relevant details.
7 Search Query Using a query object, the index database is then checked to get the relevant details and the content documents.
8 Render Results Once the result is received, the application should decide on how to show the results to the user using User Interface. How much information is to be shown at first look and so on.

これらの基本的な操作とは別に、検索アプリケーションは*管理ユーザーインターフェイス*を提供し、アプリケーションの管理者がユーザープロファイルに基づいて検索レベルを制御できるようにします。 検索結果の分析は、検索アプリケーションのもう1つの重要かつ高度な側面です。

検索アプリケーションでのLuceneの役割

Luceneは、上記のステップ2からステップ7で役割を果たし、必要な操作を行うためのクラスを提供します。 一言で言えば、Luceneは検索アプリケーションの中心であり、インデックス作成と検索に関する重要な操作を提供します。 コンテンツの取得と結果の表示は、アプリケーションパーツが処理するために残されています。

次の章では、Lucene Searchライブラリを使用して簡単な検索アプリケーションを実行します。

Lucene-環境設定

このチュートリアルでは、Spring Frameworkで作業を開始するための開発環境を準備する方法について説明します。 このチュートリアルでは、Spring Frameworkをセットアップする前に、マシンでJDK、Tomcat、Eclipseをセットアップする方法も説明します-

ステップ1-Java Development Kit(JDK)のセットアップ

最新バージョンのSDKは、OracleのJavaサイト(https://www.oracle.com/technetwork/java/javase/downloads/indexl[Java SE Downloads])からダウンロードできます。 ダウンロードしたファイルにJDKをインストールする手順が記載されています。指定された指示に従って、セットアップをインストールおよび構成します。 最後に、PATHおよびJAVA_HOME環境変数を設定して、Javaおよびjavacを含むディレクトリ(通常はそれぞれjava_install_dir/binおよびjava_install_dir)を参照します。

Windowsを実行しており、JDKをC:\ jdk1.6.0_15にインストールしている場合、C:\ autoexec.batファイルに次の行を追加する必要があります。

set PATH = C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME = C:\jdk1.6.0_15

または、Windows NT/2000/XPでは、マイコンピュータ*を右クリックし、*プロパティ詳細環境変数*の順に選択することもできます。 次に、 *PATH 値を更新し、 OK ボタンを押します。

Unix(Solaris、Linuxなど)では、SDKが/usr/local/jdk1.6.0_15にインストールされており、Cシェルを使用する場合、次を.cshrcファイルに追加します。

setenv PATH/usr/local/jdk1.6.0_15/bin:$PATH
setenv JAVA_HOME/usr/local/jdk1.6.0_15

あるいは、Borland JBuilder、Eclipse、IntelliJ IDEA、またはSun ONE Studioなどの* Integrated Development Environment(IDE)*を使用する場合は、単純なプログラムをコンパイルして実行し、IDEがJavaのインストール場所を認識していることを確認します。 IDEのドキュメントに記載されています。

ステップ2-Eclipse IDEのセットアップ

このチュートリアルのすべての例は、 Eclipse IDE を使用して作成されています。 そのため、最新バージョンのEclipseをマシンにインストールすることをお勧めします。

Eclipse IDEをインストールするには、https://www.eclipse.org/downloads/から最新のEclipseバイナリをダウンロードします。 インストールをダウンロードしたら、バイナリ配布物を便利な場所に解凍します。 たとえば、Windowsの C:\ eclipse 、Linux/Unix /usr/local/eclipseで、最後にPATH変数を適切に設定します。

Eclipseは、Windowsマシンで次のコマンドを実行することで開始できます。または、 eclipse.exe をダブルクリックするだけです

 %C:\eclipse\eclipse.exe

Eclipseは、Unix(Solaris、Linuxなど)マシンで次のコマンドを実行することで起動できます-

$/usr/local/eclipse/eclipse

正常に起動した後、次の結果が表示されます-

Eclipseホームページ

ステップ3-Lucene Frameworkライブラリのセットアップ

起動が成功したら、Luceneフレームワークのセットアップに進むことができます。 以下は、フレームワークをダウンロードしてマシンにインストールする簡単な手順です。

https://archive.apache.org/dist/lucene/java/3.6.2/

  • LuceneをWindowsにインストールするか、Unixにインストールするかを選択してから、次のステップに進み、Windowsの.zipファイルとUnixの.tzファイルをダウンロードします。
  • Luceneフレームワークバイナリの適切なバージョンをhttps://archive.apache.org/dist/lucene/java/からダウンロードします。
  • このチュートリアルを書いている時点で、Windowsマシンにlucene-3.6.2.zipをダウンロードしました。ダウンロードしたファイルを解凍すると、C:\ lucene-3.6.2内のディレクトリ構造が次のようになります。

Luceneディレクトリ

すべてのLuceneライブラリは、ディレクトリ C:\ lucene-3.6.2 にあります。 それ以外の場合は、このディレクトリでCLASSPATH変数を適切に設定してください。そうしないと、アプリケーションの実行中に問題が発生します。 Eclipseを使用している場合、すべての設定はEclipseを介して行われるため、CLASSPATHを設定する必要はありません。

この最後の手順が完了したら、次の章で説明する最初のLuceneの例に進む準備ができています。

Lucene-最初のアプリケーション

この章では、Lucene Frameworkを使用した実際のプログラミングについて学習します。 Luceneフレームワークを使用して最初の例を書き始める前に、リンク:/lucene/lucene_environment [Lucene-Environment Setup]チュートリアルで説明されているように、Lucene環境を適切にセットアップしていることを確認する必要があります。 Eclipse IDEの実用的な知識があることが推奨されます。

ここで、見つかった検索結果の数を出力する簡単な検索アプリケーションを作成します。 このプロセス中に作成されたインデックスのリストも表示されます。

ステップ1-Javaプロジェクトの作成

最初のステップは、Eclipse IDEを使用して簡単なJavaプロジェクトを作成することです。 File> New→ Project オプションに従い、最後にウィザードリストから Java Project ウィザードを選択します。 次のようにウィザードウィンドウを使用して、プロジェクトに LuceneFirstApplication という名前を付けます-

プロジェクト作成ウィザード

プロジェクトが正常に作成されると、次のコンテンツが Project Explorer に表示されます-

Lucene First Application Directories

ステップ2-必要なライブラリを追加する

プロジェクトにLuceneコアフレームワークライブラリを追加しましょう。 これを行うには、プロジェクト名 LuceneFirstApplication を右クリックし、コンテキストメニューで使用可能な次のオプションに従います。*ビルドパス→ビルドパスの設定*を使用して、Javaビルドパスウィンドウを表示します-

Javaビルドパス

  • ライブラリ*タブにある*外部JARを追加*ボタンを使用して、Luceneインストールディレクトリから次のコアJARを追加します-
  • lucene-core-3.6.2

手順3-ソースファイルの作成

*LuceneFirstApplication* プロジェクトの下に実際のソースファイルを作成しましょう。 まず、* com.finddevguides.lucene。*というパッケージを作成する必要があります。これを行うには、パッケージエクスプローラーのセクションでsrcを右クリックし、オプション[*新規->パッケージ*]に従います。

次に、 com.finddevguides.lucene パッケージの下に LuceneTester.java およびその他のJavaクラスを作成します。

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

Searcher.java

このクラスは、インデクサーによって作成されたインデックスを検索して、要求されたコンテンツを検索するために使用されます。

package com.finddevguides.lucene;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class Searcher {

   IndexSearcher indexSearcher;
   QueryParser queryParser;
   Query query;

   public Searcher(String indexDirectoryPath)
      throws IOException {
      Directory indexDirectory =
         FSDirectory.open(new File(indexDirectoryPath));
      indexSearcher = new IndexSearcher(indexDirectory);
      queryParser = new QueryParser(Version.LUCENE_36,
         LuceneConstants.CONTENTS,
         new StandardAnalyzer(Version.LUCENE_36));
   }

   public TopDocs search( String searchQuery)
      throws IOException, ParseException {
      query = queryParser.parse(searchQuery);
      return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
   }

   public Document getDocument(ScoreDoc scoreDoc)
      throws CorruptIndexException, IOException {
      return indexSearcher.doc(scoreDoc.doc);
   }

   public void close() throws IOException {
      indexSearcher.close();
   }
}

LuceneTester.java

このクラスは、luceneライブラリのインデックス作成と検索機能をテストするために使用されます。

package com.finddevguides.lucene;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

public class LuceneTester {

   String indexDir = "E:\\Lucene\\Index";
   String dataDir = "E:\\Lucene\\Data";
   Indexer indexer;
   Searcher searcher;

   public static void main(String[] args) {
      LuceneTester tester;
      try {
         tester = new LuceneTester();
         tester.createIndex();
         tester.search("Mohan");
      } catch (IOException e) {
         e.printStackTrace();
      } catch (ParseException 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");
   }

   private void search(String searchQuery) throws IOException, ParseException {
      searcher = new Searcher(indexDir);
      long startTime = System.currentTimeMillis();
      TopDocs hits = searcher.search(searchQuery);
      long endTime = System.currentTimeMillis();

      System.out.println(hits.totalHits +
         " documents found. Time :" + (endTime - startTime));
      for(ScoreDoc scoreDoc : hits.scoreDocs) {
         Document doc = searcher.getDocument(scoreDoc);
            System.out.println("File: "
            + doc.get(LuceneConstants.FILE_PATH));
      }
      searcher.close();
   }
}

ステップ4-データとインデックスのディレクトリ作成

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

ステップ5-プログラムの実行

ソース、生データ、データディレクトリ、インデックスディレクトリの作成が完了したら、プログラムをコンパイルして実行する準備が整います。 これを行うには、 LuceneTester.Java ファイルタブをアクティブのままにし、Eclipse IDEで使用可能な Run オプションを使用するか、 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
1 documents found. Time :0
File: E:\Lucene\Data\record4.txt

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

Lucene Index Directory

Lucene-インデックスクラス

インデックス作成プロセスは、Luceneが提供するコア機能の1つです。 次の図は、インデックス作成プロセスとクラスの使用を示しています。 IndexWriter は、インデックス作成プロセスの最も重要なコアコンポーネントです。

インデックス作成プロセス

*Field* を含む *Document* をIndexWriterに追加します。IndexWriterは *Analyzer* を使用して *Document* を分析し、必要に応じてインデックスを作成/開く/編集し、 *Directoryに格納/更新します。* 。 IndexWriterは、インデックスの更新または作成に使用されます。 インデックスの読み取りには使用されません。

インデックスクラス

以下は、インデックス作成プロセスで一般的に使用されるクラスのリストです。

S.No. Class & Description
1

IndexWriter

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

2

Directory

このクラスは、インデックスの保存場所を表します。

3

Analyzer

このクラスは、ドキュメントを分析し、インデックス付けされるテキストからトークン/単語を取得します。 分析が行われないと、IndexWriterはインデックスを作成できません。

4

Document

このクラスは、物理ドキュメントのコンテンツ、そのメタデータなどを含むことができるオブジェクトであるフィールドを持つ仮想ドキュメントを表します。 アナライザーはドキュメントのみを理解できます。

5

Field

これは、最下位ユニットまたはインデックス作成プロセスの開始点です。 キーを使用してインデックス付けされる値を識別するキー値ペアの関係を表します。 文書のコンテンツを表すために使用されるフィールドには「コンテンツ」としてキーがあり、値には文書のテキストまたは数値コンテンツの一部またはすべてが含まれていると仮定します。 Luceneは、テキストまたは数値コンテンツのみにインデックスを付けることができます。

Lucene-クラスの検索

検索のプロセスは、Luceneが提供するコア機能の1つです。 そのフローは、インデックス作成プロセスのフローに似ています。 Luceneの基本検索は、次のクラスを使用して実行できます。これらのクラスは、すべての検索関連操作の基礎クラスとも呼ばれます。

クラスを検索する

以下は、検索プロセス中に一般的に使用されるクラスのリストです。

S.No. Class & Description
1

IndexSearcher

このクラスは、インデックス作成プロセス後に作成されたインデックスを読み取り/検索するコアコンポーネントとして機能します。 インデックスを含む場所を指すディレクトリインスタンスを取ります。

2

Term

このクラスは、検索の最下位単位です。 インデックス作成プロセスのフィールドに似ています。

3

Query

クエリは抽象クラスであり、さまざまなユーティリティメソッドが含まれ、Luceneが検索プロセス中に使用するすべてのタイプのクエリの親です。

4

TermQuery

TermQueryは、最も一般的に使用されるクエリオブジェクトであり、Luceneが利用できる多くの複雑なクエリの基盤です。

5

TopDocs

TopDocsは、検索条件に一致する上位N個の検索結果を指します。 これは、検索結果の出力であるドキュメントを指すポインターの単純なコンテナーです。

Lucene-インデックス作成プロセス

インデックス作成プロセスは、Luceneが提供するコア機能の1つです。 次の図は、インデックス作成プロセスとクラスの使用を示しています。 IndexWriterは、インデックス作成プロセスの最も重要なコアコンポーネントです。

インデックス作成プロセス

_Field(s)_を含む_Document(s)_をIndexWriterに追加し、_Analyzer_を使用してドキュメントを分析し、必要に応じて_creates/open/edit_インデックスを作成し、_Directory_に格納/更新します。 _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を作成するには、次の手順に従ってください-

  • ステップ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);
}

インデックス作成プロセスを開始

次のプログラムは、インデックス作成プロセスを開始する方法を示しています-

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. You can also use the project created in Lucene - 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 the 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で利用可能な Run オプションを使用するか、 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

Lucene-インデックス作成操作

この章では、インデックス作成の4つの主要な操作について説明します。 これらの操作はさまざまな時に役立ち、ソフトウェア検索アプリケーション全体で使用されます。

インデックス作成操作

以下は、インデックス作成プロセス中に一般的に使用される操作のリストです。

S.No. Operation & Description
1

Add Document

この操作は、インデックス作成プロセスの初期段階で、新しく利用可能なコンテンツにインデックスを作成するために使用されます。

2

Update Document

この操作は、更新されたコンテンツの変更を反映するためにインデックスを更新するために使用されます。 インデックスの再作成に似ています。

3

Delete Document

この操作は、索引を更新して、索引付け/検索する必要のない文書を除外するために使用されます。

4

Field Options

フィールドオプションは、フィールドのコンテンツを検索可能にする方法を指定または制御します。

Lucene-検索操作

検索プロセスは、Luceneが提供するコア機能の1つです。 次の図は、プロセスとその使用法を示しています。 IndexSearcherは、検索プロセスの中核コンポーネントの1つです。

検索プロセス

最初に_indexes_を含む_Directory_を作成し、それを_IndexReader_を使用して_Directory_を開く_IndexSearcher_に渡します。 次に、_Term_を使用して_Query_を作成し、_Query_をサーチャーに渡すことで、_IndexSearcher_を使用して検索を行います。 _IndexSearcher_は、検索操作の結果である_Document_のドキュメントIDとともに検索の詳細を含む_TopDocs_オブジェクトを返します。

ここでは、段階的なアプローチを示し、基本的な例を使用してインデックス作成プロセスを理解するのに役立ちます。

QueryParserを作成する

QueryParserクラスは、ユーザーが入力した入力をLuceneの理解可能な形式のクエリに解析します。 QueryParserを作成するには、次の手順に従います-

  • ステップ1 *-QueryParserのオブジェクトを作成します。
  • ステップ2 *-このクエリを実行するバージョン情報とインデックス名を持つ標準アナライザーで作成されたQueryParserオブジェクトを初期化します。
QueryParser queryParser;

public Searcher(String indexDirectoryPath) throws IOException {

   queryParser = new QueryParser(Version.LUCENE_36,
      LuceneConstants.CONTENTS,
      new StandardAnalyzer(Version.LUCENE_36));
}

IndexSearcherを作成する

IndexSearcherクラスは、検索プロセス中に検索者がインデックスを作成するコアコンポーネントとして機能します。 IndexSearcherを作成するには、次の手順に従います-

  • ステップ1 *-IndexSearcherのオブジェクトを作成します。
  • ステップ2 *-インデックスを保存する場所をポイントするLuceneディレクトリを作成します。
  • ステップ3 *-インデックスディレクトリで作成されたIndexSearcherオブジェクトを初期化します。
IndexSearcher indexSearcher;

public Searcher(String indexDirectoryPath) throws IOException {
   Directory indexDirectory =
      FSDirectory.open(new File(indexDirectoryPath));
   indexSearcher = new IndexSearcher(indexDirectory);
}

検索する

検索を行うには、次の手順に従ってください-

  • ステップ1 *-QueryParserを介して検索式を解析することにより、Queryオブジェクトを作成します。
  • ステップ2 *-IndexSearcher.search()メソッドを呼び出して検索を行います。
Query query;

public TopDocs search( String searchQuery) throws IOException, ParseException {
   query = queryParser.parse(searchQuery);
   return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
}

ドキュメントを入手する

次のプログラムは、ドキュメントを取得する方法を示しています。

public Document getDocument(ScoreDoc scoreDoc)
   throws CorruptIndexException, IOException {
   return indexSearcher.doc(scoreDoc.doc);
}

IndexSearcherを閉じる

次のプログラムは、IndexSearcherを閉じる方法を示しています。

public void close() throws IOException {
   indexSearcher.close();
}

応用例

検索プロセスをテストするためのテスト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 Lucene - First Application chapter as such for this chapter to understand the searching process.
2 Create LuceneConstants.java,TextFileFilter.java and Searcher.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");
   }
}

Searcher.java

このクラスは、未加工データで作成されたインデックスを読み取り、Luceneライブラリを使用してデータを検索するために使用されます。

package com.finddevguides.lucene;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class Searcher {

   IndexSearcher indexSearcher;
   QueryParser queryParser;
   Query query;

   public Searcher(String indexDirectoryPath) throws IOException {
      Directory indexDirectory =
         FSDirectory.open(new File(indexDirectoryPath));
      indexSearcher = new IndexSearcher(indexDirectory);
      queryParser = new QueryParser(Version.LUCENE_36,
         LuceneConstants.CONTENTS,
         new StandardAnalyzer(Version.LUCENE_36));
   }

   public TopDocs search( String searchQuery)
      throws IOException, ParseException {
      query = queryParser.parse(searchQuery);
      return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
   }

   public Document getDocument(ScoreDoc scoreDoc)
      throws CorruptIndexException, IOException {
      return indexSearcher.doc(scoreDoc.doc);
   }

   public void close() throws IOException {
      indexSearcher.close();
   }
}

LuceneTester.java

このクラスは、Luceneライブラリの検索機能をテストするために使用されます。

package com.finddevguides.lucene;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

public class LuceneTester {

   String indexDir = "E:\\Lucene\\Index";
   String dataDir = "E:\\Lucene\\Data";
   Searcher searcher;

   public static void main(String[] args) {
      LuceneTester tester;
      try {
         tester = new LuceneTester();
         tester.search("Mohan");
      } catch (IOException e) {
         e.printStackTrace();
      } catch (ParseException e) {
         e.printStackTrace();
      }
   }

   private void search(String searchQuery) throws IOException, ParseException {
      searcher = new Searcher(indexDir);
      long startTime = System.currentTimeMillis();
      TopDocs hits = searcher.search(searchQuery);
      long endTime = System.currentTimeMillis();

      System.out.println(hits.totalHits +
         " documents found. Time :" + (endTime - startTime) +" ms");
      for(ScoreDoc scoreDoc : hits.scoreDocs) {
         Document doc = searcher.getDocument(scoreDoc);
         System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH));
      }
      searcher.close();
   }
}

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

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

プログラムを実行する

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

1 documents found. Time :29 ms
File: E:\Lucene\Data\record4.txt

Lucene-クエリプログラミング

前の章* Lucene-検索操作*で見てきましたが、LuceneはIndexSearcherを使用して検索を行い、QueryParserによって作成されたQueryオブジェクトを入力として使用します。 この章では、さまざまな種類のQueryオブジェクトと、それらをプログラムで作成するさまざまな方法について説明します。 さまざまなタイプのQueryオブジェクトを作成すると、実行する検索の種類を制御できます。

ユーザーに検索結果を制限するための複数のオプションが与えられる多くのアプリケーションによって提供される高度な検索の場合を考えてみましょう。 クエリプログラミングにより、同じことが非常に簡単に実現できます。

以下は、やがて議論するクエリの種類のリストです。

S.No. Class & Description
1

TermQuery

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

2

TermRangeQuery

TermRangeQueryは、テキスト用語の範囲を検索するときに使用されます。

3

PrefixQuery

PrefixQueryは、インデックスが指定された文字列で始まるドキュメントを照合するために使用されます。

4

BooleanQuery

BooleanQueryは、 AND、OR 、または NOT 演算子を使用した複数のクエリの結果であるドキュメントの検索に使用されます。

5

PhraseQuery

フレーズクエリは、特定の用語のシーケンスを含むドキュメントを検索するために使用されます。

6

WildCardQuery

WildcardQueryは、任意の文字シーケンスに「*」などのワイルドカードを使用してドキュメントを検索するために使用されますか? 単一の文字に一致します。

7

FuzzyQuery

FuzzyQueryは、編集距離アルゴリズムに基づいた近似検索であるファジー実装を使用してドキュメントを検索するために使用されます。

8

MatchAllDocsQuery

名前が示すとおり、MatchAllDocsQueryはすべてのドキュメントに一致します。

Lucene-分析

前の章の1つで、Luceneは_IndexWriter_を使用して_Analyzer_を使用して_Document(s)_を分析し、必要に応じてインデックスを作成/開く/編集することを確認しました。 この章では、分析プロセス中に使用されるさまざまなタイプのアナライザーオブジェクトおよびその他の関連オブジェクトについて説明します。 分析プロセスとアナライザーの仕組みを理解することで、Luceneがどのようにドキュメントにインデックスを付けるかを知ることができます。

以下は、やがて議論するオブジェクトのリストです。

S.No. Class & Description
1

Token

トークンは、ドキュメント内のテキストまたは単語を、メタデータ(位置、開始オフセット、終了オフセット、トークンタイプ、および位置の増分)などの関連する詳細とともに表します。

2

TokenStream

TokenStreamは分析プロセスの出力であり、一連のトークンで構成されています。 これは抽象クラスです。

3

Analyzer

これは、すべてのタイプのアナライザーの抽象基本クラスです。

4

WhitespaceAnalyzer

このアナライザーは、空白に基づいて文書内のテキストを分割します。

5

SimpleAnalyzer

このアナライザーは、文字以外の文字に基づいて文書内のテキストを分割し、テキストを小文字にします。

6

StopAnalyzer

このアナライザーはSimpleAnalyzerとして機能し、* 'a'、 'an'、 'the'、*などの一般的な単語を削除します。

7

StandardAnalyzer

これは最も洗練されたアナライザーであり、名前、電子メールアドレスなどを処理できます。 各トークンを小文字にし、一般的な単語や句読点がある場合は削除します。

Lucene-ソート

この章では、Luceneがデフォルトで検索結果を提供するか、必要に応じて操作できるソート順について説明します。

関連性による並べ替え

これは、Luceneが使用するデフォルトのソートモードです。 Luceneは、最も関連性の高いヒットで結果を提供します。

private void sortUsingRelevance(String searchQuery)
   throws IOException, ParseException {
   searcher = new Searcher(indexDir);
   long startTime = System.currentTimeMillis();

  //create a term to search file name
   Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);
  //create the term query object
   Query query = new FuzzyQuery(term);
   searcher.setDefaultFieldSortScoring(true, false);
  //do the search
   TopDocs hits = searcher.search(query,Sort.RELEVANCE);
   long endTime = System.currentTimeMillis();

   System.out.println(hits.totalHits +
      " documents found. Time :" + (endTime - startTime) + "ms");
   for(ScoreDoc scoreDoc : hits.scoreDocs) {
      Document doc = searcher.getDocument(scoreDoc);
      System.out.print("Score: "+ scoreDoc.score + " ");
      System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH));
   }
   searcher.close();
}

IndexOrderによる並べ替え

この並べ替えモードはLuceneで使用されます。 ここでは、最初にインデックス付けされたドキュメントが検索結果の最初に表示されます。

private void sortUsingIndex(String searchQuery)
   throws IOException, ParseException {
   searcher = new Searcher(indexDir);
   long startTime = System.currentTimeMillis();

  //create a term to search file name
   Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);
  //create the term query object
   Query query = new FuzzyQuery(term);
   searcher.setDefaultFieldSortScoring(true, false);
  //do the search
   TopDocs hits = searcher.search(query,Sort.INDEXORDER);
   long endTime = System.currentTimeMillis();

   System.out.println(hits.totalHits +
      " documents found. Time :" + (endTime - startTime) + "ms");
   for(ScoreDoc scoreDoc : hits.scoreDocs) {
      Document doc = searcher.getDocument(scoreDoc);
      System.out.print("Score: "+ scoreDoc.score + " ");
      System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH));
   }
   searcher.close();
}

応用例

ソートプロセスをテストするためのテスト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 Lucene - First Application chapter as such for this chapter to understand the searching process.
2 Create LuceneConstants.java and Searcher.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 the 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;
}

Searcher.java

このクラスは、未加工データで作成されたインデックスを読み取り、Luceneライブラリを使用してデータを検索するために使用されます。

package com.finddevguides.lucene;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class Searcher {

IndexSearcher indexSearcher;
   QueryParser queryParser;
   Query query;

   public Searcher(String indexDirectoryPath) throws IOException {
      Directory indexDirectory
         = FSDirectory.open(new File(indexDirectoryPath));
      indexSearcher = new IndexSearcher(indexDirectory);
      queryParser = new QueryParser(Version.LUCENE_36,
         LuceneConstants.CONTENTS,
         new StandardAnalyzer(Version.LUCENE_36));
   }

   public TopDocs search( String searchQuery)
      throws IOException, ParseException {
      query = queryParser.parse(searchQuery);
      return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
   }

   public TopDocs search(Query query)
      throws IOException, ParseException {
      return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
   }

   public TopDocs search(Query query,Sort sort)
      throws IOException, ParseException {
      return indexSearcher.search(query,
         LuceneConstants.MAX_SEARCH,sort);
   }

   public void setDefaultFieldSortScoring(boolean doTrackScores,
      boolean doMaxScores) {
      indexSearcher.setDefaultFieldSortScoring(
         doTrackScores,doMaxScores);
   }

   public Document getDocument(ScoreDoc scoreDoc)
      throws CorruptIndexException, IOException {
      return indexSearcher.doc(scoreDoc.doc);
   }

   public void close() throws IOException {
      indexSearcher.close();
   }
}

LuceneTester.java

このクラスは、Luceneライブラリの検索機能をテストするために使用されます。

package com.finddevguides.lucene;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TopDocs;

public class LuceneTester {

   String indexDir = "E:\\Lucene\\Index";
   String dataDir = "E:\\Lucene\\Data";
   Indexer indexer;
   Searcher searcher;

   public static void main(String[] args) {
      LuceneTester tester;
      try {
          tester = new LuceneTester();
          tester.sortUsingRelevance("cord3.txt");
          tester.sortUsingIndex("cord3.txt");
      } catch (IOException e) {
          e.printStackTrace();
      } catch (ParseException e) {
          e.printStackTrace();
      }
   }

   private void sortUsingRelevance(String searchQuery)
      throws IOException, ParseException {
      searcher = new Searcher(indexDir);
      long startTime = System.currentTimeMillis();

     //create a term to search file name
      Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);
     //create the term query object
      Query query = new FuzzyQuery(term);
      searcher.setDefaultFieldSortScoring(true, false);
     //do the search
      TopDocs hits = searcher.search(query,Sort.RELEVANCE);
      long endTime = System.currentTimeMillis();

      System.out.println(hits.totalHits +
         " documents found. Time :" + (endTime - startTime) + "ms");
      for(ScoreDoc scoreDoc : hits.scoreDocs) {
         Document doc = searcher.getDocument(scoreDoc);
         System.out.print("Score: "+ scoreDoc.score + " ");
         System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH));
      }
      searcher.close();
   }

   private void sortUsingIndex(String searchQuery)
      throws IOException, ParseException {
      searcher = new Searcher(indexDir);
      long startTime = System.currentTimeMillis();
     //create a term to search file name
      Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);
     //create the term query object
      Query query = new FuzzyQuery(term);
      searcher.setDefaultFieldSortScoring(true, false);
     //do the search
      TopDocs hits = searcher.search(query,Sort.INDEXORDER);
      long endTime = System.currentTimeMillis();

      System.out.println(hits.totalHits +
      " documents found. Time :" + (endTime - startTime) + "ms");
      for(ScoreDoc scoreDoc : hits.scoreDocs) {
         Document doc = searcher.getDocument(scoreDoc);
         System.out.print("Score: "+ scoreDoc.score + " ");
         System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH));
      }
      searcher.close();
   }
}

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

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

プログラムを実行する

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

10 documents found. Time :31ms
Score: 1.3179655 File: E:\Lucene\Data\record3.txt
Score: 0.790779 File: E:\Lucene\Data\record1.txt
Score: 0.790779 File: E:\Lucene\Data\record2.txt
Score: 0.790779 File: E:\Lucene\Data\record4.txt
Score: 0.790779 File: E:\Lucene\Data\record5.txt
Score: 0.790779 File: E:\Lucene\Data\record6.txt
Score: 0.790779 File: E:\Lucene\Data\record7.txt
Score: 0.790779 File: E:\Lucene\Data\record8.txt
Score: 0.790779 File: E:\Lucene\Data\record9.txt
Score: 0.2635932 File: E:\Lucene\Data\record10.txt
10 documents found. Time :0ms
Score: 0.790779 File: E:\Lucene\Data\record1.txt
Score: 0.2635932 File: E:\Lucene\Data\record10.txt
Score: 0.790779 File: E:\Lucene\Data\record2.txt
Score: 1.3179655 File: E:\Lucene\Data\record3.txt
Score: 0.790779 File: E:\Lucene\Data\record4.txt
Score: 0.790779 File: E:\Lucene\Data\record5.txt
Score: 0.790779 File: E:\Lucene\Data\record6.txt
Score: 0.790779 File: E:\Lucene\Data\record7.txt
Score: 0.790779 File: E:\Lucene\Data\record8.txt
Score: 0.790779 File: E:\Lucene\Data\record9.txt