- Lucene - Sorting
- Lucene - Analysis
- Lucene - Query Programming
- Lucene - Search Operation
- Lucene - Indexing Operations
- Lucene - Indexing Process
- Lucene - Searching Classes
- Lucene - Indexing Classes
- Lucene - First Application
- Lucene - Environment Setup
- Lucene - Overview
- Lucene - Home
Lucene Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Lucene - Indexing Process
Indexing process is one of the core functionapty provided by Lucene. Following diagram illustrates the indexing process and use of classes. IndexWriter is the most important and core component of the indexing process.
We add Document(s) containing Field(s) to IndexWriter which analyzes the Document(s) using the Analyzer and then creates/open/edit indexes as required and store/update them in a Directory. IndexWriter is used to update or create indexes. It is not used to read indexes.
Now we ll show you a step by step process to get a kick start in understanding of indexing process using a basic example.
Create a document
Create a method to get a lucene document from a text file.
Create various types of fields which are key value pairs containing keys as names and values as contents to be indexed.
Set field to be analyzed or not. In our case, only contents is to be analyzed as it can contain data such as a, am, are, an etc. which are not required in search operations.
Add the newly created fields to the document object and return it to the caller method.
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; }
Create a IndexWriter
IndexWriter class acts as a core component which creates/updates indexes during indexing process. Follow these steps to create a IndexWriter −
Step 1 − Create object of IndexWriter.
Step 2 − Create a Lucene directory which should point to location where indexes are to be stored.
Step 3 − Initiapze the IndexWriter object created with the index directory, a standard analyzer having version information and other required/optional parameters.
private IndexWriter writer; pubpc 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); }
Start Indexing Process
The following program shows how to start an indexing process −
private void indexFile(File file) throws IOException { System.out.println("Indexing "+file.getCanonicalPath()); Document document = getDocument(file); writer.addDocument(document); }
Example Apppcation
To test the indexing process, we need to create a Lucene apppcation test.
Step | Description |
---|---|
1 | Create a project with a name LuceneFirstApppcation under a package com.tutorialspoint.lucene as explained in the Lucene - First Apppcation chapter. You can also use the project created in Lucene - First Apppcation 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 Apppcation chapter. Keep the rest of the files unchanged. |
3 | Create LuceneTester.java as mentioned below. |
4 | Clean and build the apppcation to make sure the business logic is working as per the requirements. |
LuceneConstants.java
This class is used to provide various constants to be used across the sample apppcation.
package com.tutorialspoint.lucene; pubpc class LuceneConstants { pubpc static final String CONTENTS = "contents"; pubpc static final String FILE_NAME = "filename"; pubpc static final String FILE_PATH = "filepath"; pubpc static final int MAX_SEARCH = 10; }
TextFileFilter.java
This class is used as a .txt file filter.
package com.tutorialspoint.lucene; import java.io.File; import java.io.FileFilter; pubpc class TextFileFilter implements FileFilter { @Override pubpc boolean accept(File pathname) { return pathname.getName().toLowerCase().endsWith(".txt"); } }
Indexer.java
This class is used to index the raw data so that we can make it searchable using the Lucene pbrary.
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; pubpc class Indexer { private IndexWriter writer; pubpc 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); } pubpc 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); } pubpc int createIndex(String dataDirPath, FileFilter filter) throws IOException { //get all files in the data directory File[] files = new File(dataDirPath).pstFiles(); for (File file : files) { if(!file.isDirectory() && !file.isHidden() && file.exists() && file.canRead() && filter.accept(file) ){ indexFile(file); } } return writer.numDocs(); } }
LuceneTester.java
This class is used to test the indexing capabipty of the Lucene pbrary.
package com.tutorialspoint.lucene; import java.io.IOException; pubpc class LuceneTester { String indexDir = "E:\Lucene\Index"; String dataDir = "E:\Lucene\Data"; Indexer indexer; pubpc 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.currentTimeMilps(); numIndexed = indexer.createIndex(dataDir, new TextFileFilter()); long endTime = System.currentTimeMilps(); indexer.close(); System.out.println(numIndexed+" File indexed, time taken: " +(endTime-startTime)+" ms"); } }
Data & Index Directory Creation
We have used 10 text files from record1.txt to record10.txt containing names and other details of the students and put them in the directory E:LuceneData.
. An index directory path should be created as E:LuceneIndex. After running this program, you can see the pst 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 and the index directory, you can proceed by compipng and running your program. To do this, keep the LuceneTester.Java file tab active and use either the Run option available in the Ecppse IDE or use Ctrl + F11 to compile and run your LuceneTester apppcation. If your apppcation runs successfully, it will print the following message in Ecppse IDE s console −
Indexing E:LuceneData ecord1.txt Indexing E:LuceneData ecord10.txt Indexing E:LuceneData ecord2.txt Indexing E:LuceneData ecord3.txt Indexing E:LuceneData ecord4.txt Indexing E:LuceneData ecord5.txt Indexing E:LuceneData ecord6.txt Indexing E:LuceneData ecord7.txt Indexing E:LuceneData ecord8.txt Indexing E:LuceneData ecord9.txt 10 File indexed, time taken: 109 ms
Once you ve run the program successfully, you will have the following content in your index directory −
Advertisements