I am using SpanTerm Query for searching exact phrase in lucene. But it doesnt seem to work. Here is my code.
Indexing
IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30), false,IndexWriter.MaxFieldLength.UNLIMITED);
doc.add(new Field("contents", sb.toString(), Field.Store.YES, Field.Index.ANALYZED,Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.add(new Field("imageid", imageDocument.getImageId(), Field.Store.YES, Field.Index.NOT_ANALYZED));
doc.add(new Field("title", imageDocument.getTitle(), Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("country", imageDocument.getCountry(), Field.Store.YES, Field.Index.NOT_ANALYZED));
write.addDocument(doc);
Searching
String sentence = searchParameters.get("searchExactWord");
String[] words = sentence.split(" ");
String queryNoWord = "";
int i = 0;
SpanTermQuery [] clause = new SpanTermQuery[words.length];
for (String word : words)
{
clause[i] = new SpanTermQuery(new Term("contents",word));
i++;
}
SpanNearQuery query = new SpanNearQuery(clause, 0, true);
booleanQuery.add(query, BooleanClause.Occur.MUST);
Please guide me if I am doing it wrong???
Prateek
Step 1 − Create object of IndexSearcher. Step 2 − Create a Lucene directory which should point to location where indexes are to be stored. Step 3 − Initialize the IndexSearcher object created with the index directory.
Apache Lucene™ is a high-performance, full-featured search engine library written entirely in Java. It is a technology suitable for nearly any application that requires structured search, full-text search, faceting, nearest-neighbor search across high-dimensionality vectors, spell correction or query suggestions.
Why is Lucene faster? Lucene is very fast at searching for data because of its inverted index technique. Normally, datasources structure the data as an object or record, which in turn have fields and values.
Lucene is able to achieve fast search responses because, instead of searching the text directly, it searches an index instead. This would be the equivalent of retrieving pages in a book related to a keyword by searching the index at the back of a book, as opposed to searching the words in each page of the book.
Use Lucene Query Builder, and give double quotes around the search string. It works for exact phrase search.
Reference: http://www.lucenetutorial.com/lucene-query-builder.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With