Lucene-booleanquery

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

Lucene-BooleanQuery

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

クラス宣言

以下は org.apache.lucene.search.BooleanQuery クラスの宣言です-

public class BooleanQuery
   extends Query
      implements Iterable<BooleanClause>

フィールド

以下は、BooleanQueryのフィールドです-

*protected int minNrShouldMatch

クラスコンストラクター

次の表は、さまざまなクラスのコンストラクタを示しています-

S.No. Constructor & Description
1
  • BooleanQuery()*

空のブールクエリを作成します。

2

BooleanQuery(boolean disableCoord)

空のブールクエリを作成します。

クラスメソッド

次の表は、さまざまなクラスメソッドを示しています-

S.No. Method & Description
1

void add(BooleanClause clause)

ブールクエリに句を追加します。

2

void add(Query query, BooleanClause.Occur occur)

ブールクエリに句を追加します。

3

List<BooleanClause> clauses()

このクエリの句のリストを返します。

4

Object clone()

このクエリのクローンを返します。

5

Weight createWeight(Searcher searcher)

エキスパート:このクエリに適切なWeight実装を構築します。

6

boolean equals(Object o)

オブジェクトoがこれに等しい場合、trueを返します。

7

void extractTerms(Set terms)

エキスパート:このクエリで発生するすべての用語を用語セットに追加します。

8

BooleanClause[] getClauses()

このクエリの句のセットを返します。

9

static int getMaxClauseCount()

許可される句の最大数、デフォルトでは1024を返します。

10

int getMinimumNumberShouldMatch()

満たす必要があるオプションのBooleanClausesの最小数を取得します。

11

int hashCode()

このオブジェクトのハッシュコード値を返します。

12

boolean isCoordDisabled()

このクエリインスタンスのスコアリングで* Similarity.coord(int、int)*が無効になっている場合、trueを返します。

13

Iterator<BooleanClause> iterator()

このクエリの句の反復子を返します。

14

Query rewrite(IndexReader reader)

エキスパート:クエリをプリミティブクエリに書き換えるために呼び出されます。

15

static void setMaxClauseCount(int maxClauseCount)

BooleanQueryごとに許可される句の最大数を設定します。

16

void setMinimumNumberShouldMatch(int min)

満たす必要があるオプションのBooleanClausesの最小数を指定します。

17

String toString(String field)

このクエリのユーザーが読み取り可能なバージョンを出力します。

継承されるメソッド

このクラスは、次のクラスからメソッドを継承します-

  • org.apache.lucene.search.Query
  • java.lang.Object

使用法

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

  //create a term to search file name
   Term term1 = new Term(LuceneConstants.FILE_NAME, searchQuery1);
  //create the term query object
   Query query1 = new TermQuery(term1);

   Term term2 = new Term(LuceneConstants.FILE_NAME, searchQuery2);
  //create the term query object
   Query query2 = new PrefixQuery(term2);

   BooleanQuery query = new BooleanQuery();
   query.add(query1,BooleanClause.Occur.MUST_NOT);
   query.add(query2,BooleanClause.Occur.MUST);

  //do the search
   TopDocs hits = searcher.search(query);
   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();
}

応用例

BooleanQueryを使用して検索をテストするためのテスト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.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 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.BooleanClause;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.BooleanQuery;
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.searchUsingBooleanQuery("record1.txt","record1");
      } catch (IOException e) {
         e.printStackTrace();
      } catch (ParseException e) {
         e.printStackTrace();
      }
   }

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

     //create a term to search file name
      Term term1 = new Term(LuceneConstants.FILE_NAME, searchQuery1);
     //create the term query object
      Query query1 = new TermQuery(term1);

      Term term2 = new Term(LuceneConstants.FILE_NAME, searchQuery2);
     //create the term query object
      Query query2 = new PrefixQuery(term2);

      BooleanQuery query = new BooleanQuery();
      query.add(query1,BooleanClause.Occur.MUST_NOT);
      query.add(query2,BooleanClause.Occur.MUST);

     //do the search
      TopDocs hits = searcher.search(query);
      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からrecord10.txtまでの10個のテキストファイルを使用して、学生の名前やその他の詳細を含め、* E:\ Lucene \ Data。* link:/lucene/data.zip [Test Data]ディレクトリに配置しました。 インデックスディレクトリパスは、 E:\ Lucene \ Index として作成する必要があります。 * Lucene-インデックス作成プロセス*の章でインデックス作成プログラムを実行すると、そのフォルダーで作成されたインデックスファイルのリストを確認できます。

プログラムを実行する

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

1 documents found. Time :26ms
File: E:\Lucene\Data\record10.txt