Lucene - Primera aplicación

En este capítulo, aprenderemos la programación real con Lucene Framework. Antes de comenzar a escribir su primer ejemplo usando el marco de Lucene, debe asegurarse de haber configurado su entorno de Lucene correctamente como se explica en Lucene - Tutorial de configuración del entorno . Se recomienda que tenga el conocimiento práctico de Eclipse IDE.

Procedamos ahora escribiendo una aplicación de búsqueda simple que imprimirá el número de resultados de búsqueda encontrados. También veremos la lista de índices creados durante este proceso.

Paso 1: crear un proyecto Java

El primer paso es crear un proyecto Java simple usando Eclipse IDE. Sigue la opciónFile > New -> Project y finalmente seleccione Java Projectasistente de la lista de asistentes. Ahora nombre su proyecto comoLuceneFirstApplication utilizando la ventana del asistente de la siguiente manera:

Una vez que su proyecto se haya creado con éxito, tendrá el siguiente contenido en su Project Explorer -

Paso 2: agregue las bibliotecas necesarias

Agreguemos ahora la biblioteca del Framework principal de Lucene en nuestro proyecto. Para hacer esto, haga clic derecho en el nombre de su proyectoLuceneFirstApplication y luego siga la siguiente opción disponible en el menú contextual: Build Path -> Configure Build Path para mostrar la ventana Java Build Path de la siguiente manera:

Ahora usa Add External JARs botón disponible debajo Libraries pestaña para agregar el siguiente JAR principal desde el directorio de instalación de Lucene -

  • lucene-core-3.6.2

Paso 3: crear archivos fuente

Creemos ahora archivos fuente reales bajo el LuceneFirstApplicationproyecto. Primero necesitamos crear un paquete llamadocom.tutorialspoint.lucene. Para hacer esto, haga clic derecho en src en la sección del explorador de paquetes y siga la opción: New -> Package.

A continuación crearemos LuceneTester.java y otras clases de Java bajo el com.tutorialspoint.lucene paquete.

LuceneConstants.java

Esta clase se utiliza para proporcionar varias constantes que se utilizarán en la aplicación de muestra.

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

TextFileFilter.java

Esta clase se utiliza como .txt file filtrar.

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

Esta clase se usa para indexar los datos sin procesar para que podamos buscarlos usando la biblioteca Lucene.

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

Esta clase se utiliza para buscar los índices creados por el Indexador para buscar el contenido solicitado.

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 Document getDocument(ScoreDoc scoreDoc) 
      throws CorruptIndexException, IOException {
      return indexSearcher.doc(scoreDoc.doc);	
   }

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

LuceneTester.java

Esta clase se utiliza para probar la capacidad de indexación y búsqueda de la biblioteca lucene.

package com.tutorialspoint.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();
   }
}

Paso 4: creación del directorio de datos e índices

Hemos utilizado 10 archivos de texto de record1.txt a record10.txt que contienen nombres y otros detalles de los estudiantes y los colocamos en el directorio E:\Lucene\Data. Prueba de datos . Se debe crear una ruta de directorio de índice comoE:\Lucene\Index. Después de ejecutar este programa, puede ver la lista de archivos de índice creados en esa carpeta.

Paso 5: ejecutar el programa

Una vez que haya terminado con la creación de la fuente, los datos sin procesar, el directorio de datos y el directorio de índice, estará listo para compilar y ejecutar su programa. Para hacer esto, mantenga elLuceneTester.Java pestaña de archivo activa y utilice la Run opción disponible en Eclipse IDE o use Ctrl + F11 para compilar y ejecutar su LuceneTestersolicitud. Si la aplicación se ejecuta correctamente, imprimirá el siguiente mensaje en la consola de 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

Una vez que haya ejecutado el programa con éxito, tendrá el siguiente contenido en su index directory -