Lucene - PrefixQuery

PrefixQuery viene utilizzato per abbinare i documenti il ​​cui indice inizia con una stringa specificata.

Dichiarazione di classe

Di seguito è riportata la dichiarazione per il org.apache.lucene.search.PrefixQuery classe -

public class PrefixQuery
   extends MultiTermQuery

Costruttori di classi

La tabella seguente mostra i diversi costruttori di classi:

S.No. Costruttore e descrizione
1

PrefixQuery(Term prefix)

Costruisce una query per il termine che inizia con prefisso.

Metodi di classe

La tabella seguente mostra i diversi metodi di classe:

S.No. Metodo e descrizione
1

boolean equals(Object o)

Restituisce vero se l'oggetto o è uguale a questo.

2

protected FilteredTermEnumgetEnum(IndexReader reader)

Costruisce l'enumerazione da utilizzare, espandendo il termine del modello.

3

Term getPrefix()

Restituisce il prefisso di questa query.

4

int hashCode()

Restituisce un valore di codice hash per questo oggetto.

5

String toString(String field)

Stampa una versione leggibile dall'utente di questa query.

Metodi ereditati

Questa classe eredita i metodi dalle seguenti classi:

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

Utilizzo

private void searchUsingPrefixQuery(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 PrefixQuery(term);
   //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();
}

Applicazione di esempio

Creiamo un'applicazione Lucene di prova per testare la ricerca utilizzando PrefixQuery.

Passo Descrizione
1

Creare un progetto con un nome LuceneFirstApplication sotto un pacchetto com.tutorialspoint.lucene come spiegato nel capitolo Lucene - Prima applicazione . È inoltre possibile utilizzare il progetto creato nel capitolo Lucene - Prima applicazione in quanto tale per questo capitolo per comprendere il processo di ricerca.

2

Creare LuceneConstants.java e Searcher.java come spiegato nel capitolo Lucene - Prima applicazione . Mantieni invariato il resto dei file.

3

Crea LuceneTester.java come indicato di seguito.

4

Pulisci e crea l'applicazione per assicurarti che la logica di business funzioni secondo i requisiti.

LuceneConstants.java

Questa classe viene utilizzata per fornire varie costanti da utilizzare nell'applicazione di esempio.

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

Questa classe viene utilizzata per leggere gli indici realizzati su dati grezzi e ricercare dati utilizzando la libreria Lucene.

package com.tutorialspoint.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

Questa classe viene utilizzata per testare la capacità di ricerca della libreria Lucene.

package com.tutorialspoint.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.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.PrefixQuery;
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.searchUsingPrefixQuery("record1");
      } catch (IOException e) {
         e.printStackTrace();
      } catch (ParseException e) {
         e.printStackTrace();
      }
   }

   private void searchUsingPrefixQuery(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 PrefixQuery(term);
      //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();
   }
}

Creazione di directory di dati e indici

Abbiamo utilizzato 10 file di testo da record1.txt a record10.txt contenenti nomi e altri dettagli degli studenti e li abbiamo inseriti nella directory E:\Lucene\Data. Dati di prova . Un percorso della directory dell'indice dovrebbe essere creato comeE:\Lucene\Index. Dopo aver eseguito il programma di indicizzazione nel capitoloLucene - Indexing Process, puoi vedere l'elenco dei file indice creati in quella cartella.

Esecuzione del programma

Una volta terminata la creazione del sorgente, dei dati grezzi, della directory dei dati, della directory dell'indice e degli indici, puoi procedere compilando ed eseguendo il tuo programma. Per fare ciò, tieni il fileLuceneTester.Java scheda file attiva e utilizzare l'opzione Esegui disponibile nell'IDE Eclipse o utilizzare Ctrl + F11 per compilare ed eseguire il tuo LuceneTesterapplicazione. Se l'applicazione viene eseguita correttamente, stamperà il seguente messaggio nella console di Eclipse IDE:

2 documents found. Time :20ms
File: E:\Lucene\Data\record1.txt
File: E:\Lucene\Data\record10.txt