Lets suppose you have stored the lucene index in the filesystem with FSDirectory in folder "c:\lucenefolder". Lets say you have field "titleField" for all documents with option Field.Store.YES.
You can use query parser to search for word "mp3" :
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.store.FSDirectory;
public class Dummy {
public static void main(String[] args) throws Exception {
String queryString = "mp3";
Searcher s = new IndexSearcher(FSDirectory.getDirectory("c:\\lucenefolder"));
final QueryParser parser = new QueryParser(
"titleField",
new StandardAnalyzer());
final Hits hits = s.search(parser.parse(queryString));
int hitCount = hits.length();
if (hitCount == 0) {
System.out.println("No results for for \"" + queryString + "\"");
} else {
System.out.println("Matched results for \"" + queryString + "\":");
// Iterate the Hits object
for (int i = 0; i < hitCount; i++) {
Document doc = hits.doc(i);
System.out.println("doc#" + (i + 1) + ". " + doc.get("titleField"));
}
}
}
}
Another way to make the query is to build it by your self:
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;
public class Dummy {
public static void main(String[] args) throws Exception {
String queryString = "mp3";
Searcher s = new IndexSearcher(FSDirectory.getDirectory("c:\\lucenefolder"));
final Query q = new TermQuery(new Term("titleField",queryString));
final Hits hits = s.search(q);
int hitCount = hits.length();
if (hitCount == 0) {
System.out.println("No results for for \"" + queryString + "\"");
} else {
System.out.println("Matched results for \"" + queryString + "\":");
// Iterate the Hits object
for (int i = 0; i < hitCount; i++) {
Document doc = hits.doc(i);
System.out.println("doc#" + (i + 1) + ". " + doc.get("titleField"));
}
}
}
}
You can make query by java objects like this(result should contain both words mp3 and radio):
final BooleanQuery q = new BooleanQuery();
q.add(
new TermQuery(new Term("titleField","mp3")),
BooleanClause.Occur.MUST
);
q.add(
new TermQuery(new Term("titleField","radio")),
BooleanClause.Occur.MUST
);
Query that issues result that contains word "mp3" or word "radio"
final BooleanQuery q = new BooleanQuery();
q.add(
new TermQuery(new Term("titleField","mp3")),
BooleanClause.Occur.SHOULD
);
q.add(
new TermQuery(new Term("titleField","radio")),
BooleanClause.Occur.SHOULD
);