lucene

Search Lucene Index

Photo of Ilias TsagklisIlias TsagklisNovember 11th, 2012Last Updated: November 11th, 2012
0 58 1 minute read
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 aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
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 ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Ilias TsagklisIlias TsagklisNovember 11th, 2012Last Updated: November 11th, 2012
0 58 1 minute read
Photo of Ilias Tsagklis

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.