lucene

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:

Ilias Tsagklis

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

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button