Apache Lucene is a widely used text search engine and in this tutorial we will see how to create an indext of the database records

As you can see in the below snippet in order to create an index we need to follow some easy steps.As an example we will create an index for the tutorials of Java-Only.Each document will contain the tutorial,its title and its id in the database.

package com.javaonly.actions;

import java.io.*;
import java.util.*;

import org.apache.lucene.analysis.core.*;
import org.apache.lucene.document.*;

import org.apache.lucene.index.*;

import org.apache.lucene.store.*;
import org.apache.lucene.util.*;



import com.javaonly.dao.*;
import com.javaonly.model.*;


public class IndexingAction {

	public static void main(String args[]) throws IOException{
		TutorialDao tutorialsDao=new TutorialDao();
		IndexWriter indexWriter;
		Directory dir;
		//Define the file that the index will be saved and create a File Directory
		File indexFile=new File("C:\\index");
		dir=FSDirectory.open(indexFile);
		//Configure indexer with a Standard Analyser
		IndexWriterConfig config=new IndexWriterConfig(Version.LUCENE_45,new StandardAnalyzer(Version.LUCENE_45));
		
		config.setOpenMode(OpenMode.CREATE);
		indexWriter=new IndexWriter(dir,config);
		
		//Retrieve all tutorials and create a lucene document
		List tutorialList=tutorialsDao.findAll();
		
		for (Tutorial tutorial : tutorialList) {
			Document doc=new Document();
			TextField titleField = new TextField("title", tutorial.getTitle(), Field.Store.YES);
			TextField bodyField=new TextField("body",tutorial.getBody(),Field.Store.YES);
			LongField idField=new LongField("id",tutorial.getId(),Field.Store.YES);
			doc.add(titleField);
			
			doc.add(bodyField);
			doc.add(idField);
			//add document in the index
			indexWriter.addDocument(doc);
		}
	}
	
}

Note that in the above example we set Open Mode of IndexWriterConfig at CREATE.This is because we need to create the index.Later,in case we need to add new tutorials in the index, the open mode must be set to CREATE_OR_UPDATE.This way the index writer will append the new documents in the existing index instead of creating new index every time a new document is created