Slim
Slim

Reputation: 1276

Lucene query result : get the words in the returned documents that were found by the query

In order to present highlighted match-words in the documents that were returned by Lucene queries, Lucene search result may contain the words that were used to return the doc as matching my request.

For example :

How to achieve this with Lucene? Manually I can't handle cats or dogs or any difference between requested words and returned words.

Upvotes: 1

Views: 413

Answers (1)

femtoRgon
femtoRgon

Reputation: 33351

Use Lucene's Highlighter. Something like this:

//By default, this formatter will wrap highlights with <b>, but that is configurable.
Formatter formatter = new SimpleHTMLFormatter(); 
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(formatter, queryScorer);
//You can set a fragmenter as well, by default it will split into fragments 100 chars in size, using SimpleFragmenter.

String highlightedSnippet = highlighter.getBestFragment(myAnalyzer, fieldName, fieldContent);

Upvotes: 1

Related Questions