Friday 14 March 2008

How to search indexes using lucene?

To search through indexes using your java code is easy. You can search through your indexes created by lucene using lucene API. Lucene-core-2.2.0.jar.

Following is the code usage showing how to search through lucene index.

IndexReader reader = null;

reader = IndexReader.open("C:\\var\\lucene\\indexes\\Document"); (path of your lucene index i.e. segments.gen)

Searcher searcher = new IndexSearcher(reader);

Analyzer analyzer = new StandardAnalyzer();

MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[]{"content", "title", "description"}, analyzer); ('content','title','description' are the fields which we want to search in index)

Query query = parser.parse('searchString');

Hits hits = searcher.search(query);

Once you get the hits object you can find any data that is saved in index using the hits object.

No comments: