Home » Core Java » apache » lucene » Search Lucene Index

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Search Lucene Index

package com.javacodegeeks.lucene;
 
import java.io.File;
 
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
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 SimpleSearcher {
    
    public static void main(String[] args) throws Exception {

  

  File indexDir = new File("c:/index/");

  String query = "lucene";

  int hits = 100;

  

  SimpleSearcher searcher = new SimpleSearcher();

  searcher.searchIndex(indexDir, query, hits);

  
    }
    
    private void searchIndex(File indexDir, String queryStr, int maxHits) 


throws Exception {

  

  Directory directory = FSDirectory.open(indexDir);
 

  IndexSearcher searcher = new IndexSearcher(directory);

  QueryParser parser = new QueryParser(Version.LUCENE_30, 


 "contents", new SimpleAnalyzer());

  Query query = parser.parse(queryStr);

  

  TopDocs topDocs = searcher.search(query, maxHits);

  

  ScoreDoc[] hits = topDocs.scoreDocs;

  for (int i = 0; i < hits.length; i++) {


int docId = hits[i].doc;


Document d = searcher.doc(docId);


System.out.println(d.get("filename"));

  }

  

  System.out.println("Found " + hits.length);

  
    }
 
}

Related Article:

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of