I am trying to write a simple program using Lucene 2.9.4 which searches for a phrase query but I am getting 0 hits
public class HelloLucene {
public static void main(String[] args) throws IOException, ParseException{
// TODO Auto-generated method stub
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
Directory index = new RAMDirectory();
IndexWriter w = new IndexWriter(index,analyzer,true,IndexWriter.MaxFieldLength.UNLIMITED);
addDoc(w, "Lucene in Action");
addDoc(w, "Lucene for Dummies");
addDoc(w, "Managing Gigabytes");
addDoc(w, "The Art of Computer Science");
w.close();
PhraseQuery pq = new PhraseQuery();
pq.add(new Term("content", "lucene"),0);
pq.add(new Term("content", "in"),1);
pq.setSlop(0);
int hitsPerPage = 10;
IndexSearcher searcher = new IndexSearcher(index,true);
TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
searcher.search(pq, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
System.out.println("Found " + hits.length + " hits.");
for(int i=0; i<hits.length; i++){
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println((i+1)+ "." + d.get("content"));
}
searcher.close();
}
public static void addDoc(IndexWriter w, String value)throws IOException{
Document doc = new Document();
doc.add(new Field("content", value, Field.Store.YES, Field.Index.NOT_ANALYZED));
w.addDocument(doc);
}
}
Please tell me what is wrong. I have also tried using QueryParser as following
String querystr ="\"Lucene in Action\"";
Query q = new QueryParser(Version.LUCENE_29, "content",analyzer).parse(querystr);
But this is also not working.