Lucene - PhraseQuery



PhraseQuery class is used to search documents which contain a particular sequence of terms.

Class Declaration

Following is the declaration for org.apache.lucene.search.PhraseQuery class −

public class PhraseQuery
   extends Query
S.No. Constructor & Description
1

PhraseQuery(int slop, String field, String... terms)

Create a phrase query which will match documents that contain the given list of terms at consecutive positions in field, and at a maximum edit distance of slop.

2

PhraseQuery(int slop, String field, BytesRef... terms)

Create a phrase query which will match documents that contain the given list of terms at consecutive positions in field, and at a maximum edit distance of slop.

3

PhraseQuery(String field, String... terms)

Create a phrase query which will match documents that contain the given list of terms at consecutive positions in field.

4

PhraseQuery(String field, BytesRef... terms)

Create a phrase query which will match documents that contain the given list of terms at consecutive positions in field.

S.No. Method & Description
1

List<BooleanClause> clauses()

Return a list of the clauses of this BooleanQuery.

2

Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost)

Expert: Constructs an appropriate Weight implementation for this query.

3

boolean equals(Object other)

Returns true iff o is equal to this.

4

String getField()

Returns the field this query applies to

5

int[] getPositions()

Returns the relative positions of terms in this phrase.

6

int getSlop()

Return the slop for this PhraseQuery.

7

Term[] getTerms()

Returns the list of terms in this phrase.

8

int hashCode()

Returns a hash code value for this object.

9

Query rewrite(IndexSearcher indexSearcher)

Expert: called to re-write queries into primitive queries.

10

static float termPositionsCost(TermsEnum termsEnum)

Returns an expected cost in simple operations of processing the occurrences of a term in a document that contains the term.

11

String toString(String f)

Prints a user-readable version of this query.

12

void visit(QueryVisitor visitor)

Recurse through the query tree, visiting any child queries.

Methods Inherited

This class inherits methods from the following classes −

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

Usage of PhraseQuery

private void searchUsingPhraseQuery(String[] phrases)
   throws IOException, ParseException {
   searcher = new Searcher(indexDir);
   long startTime = System.currentTimeMillis();
   PhraseQuery.Builder queryBuilder = new PhraseQuery.Builder();
   queryBuilder.setSlop(0);

   for(String word:phrases) {
      queryBuilder.add(new Term(LuceneConstants.FILE_NAME,word));
   }

   PhraseQuery query = queryBuilder.build();

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

Example Application

To test search using BooleanQuery, let us create a test Lucene application.

Step Description
1

Create a project with a name LuceneFirstApplication under a package com.tutorialspoint.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 business logic is working as per the requirements.

LuceneConstants.java

This class is used to provide various constants to be used across the sample application.

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

Searcher.java

This class is used to read the indexes made on raw data and searches data using the Lucene library.

package com.tutorialspoint.lucene;

import java.io.IOException;
import java.nio.file.Paths;
import java.text.ParseException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.DirectoryReader;
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.FSDirectory;
import org.apache.lucene.util.QueryBuilder;

public class Searcher {

   IndexSearcher indexSearcher;
   QueryBuilder queryBuilder;
   Query query;

   public Searcher(String indexDirectoryPath) 
      throws IOException {
      DirectoryReader indexDirectory = DirectoryReader.open(FSDirectory.open(Paths.get(indexDirectoryPath)));
      indexSearcher = new IndexSearcher(indexDirectory);
      StandardAnalyzer analyzer = new StandardAnalyzer();
      queryBuilder = new QueryBuilder(analyzer);
   }

   public TopDocs search( String searchQuery) 
      throws IOException, ParseException {
      query = queryBuilder.createPhraseQuery(LuceneConstants.CONTENTS, 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.storedFields().document(scoreDoc.doc);	
   }
}

LuceneTester.java

This class is used to test the searching capability of the Lucene library.

package com.tutorialspoint.lucene;

import java.io.IOException;
import java.text.ParseException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

public class LuceneTester {

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

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

   private void searchUsingPhraseQuery(String[] phrases)
      throws IOException, ParseException {
      searcher = new Searcher(indexDir);
      long startTime = System.currentTimeMillis();

      PhraseQuery.Builder queryBuilder = new PhraseQuery.Builder();
      queryBuilder.setSlop(0);

      for(String word:phrases) {
         queryBuilder.add(new Term(LuceneConstants.FILE_NAME,word));
      }

      PhraseQuery query = queryBuilder.build();

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

Data & Index Directory Creation

I've used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory D:\Lucene\Data. Test Data. An index directory path should be created as D:\Lucene\Index. After running the indexing program in the chapter Lucene - Indexing Process, you can see the list of index files created in that folder.

Running the Program

Once you are done with the creation of the source, the raw data, the data directory, the index directory and the indexes, you can proceed by compiling and running your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Eclipse IDE or use Ctrl + F11 to compile and run your LuceneTester application. If your application runs successfully, it will print the following message in Eclipse IDE's console −

Output

1 hits documents found. Time :31ms
File: D:\lucene\Data\record1.txt
Advertisements