0
votes

I'm using Lucene.net to implement fulltext search feature in an Asp.net application. The search result page should high light the match items. I got the instance of Lucene.Net.Search.Hits and used .Doc(int i) method to get Lucene Document.

But I don't know how to get the position of match item by existing method or property of some Lucene class. Does Lucene.net provide any feature to support high light query string?

2

2 Answers

1
votes

You can use Highlighter or FastVectorHighlighter which can be found in contrib

0
votes

As the previous answerer said, you should use either Highlighter or FastVectorHighlighter from contrib.

Here's an example of using Highlighter lib to get highlighted fragments:

Formatter formatter = new SimpleHTMLFormatter("<span><b>", "</b></span>");
Lucene.Net.Highlight.Scorer scorer = new QueryScorer(query, field);
Lucene.Net.Highlight.Encoder encoder = new SimpleHTMLEncoder();
var highlighter = new Highlighter(formatter, encoder, scorer);
highlighter.SetTextFragmenter(new SimpleFragmenter(100));

string[] fragments = 
    highlighter.GetBestFragments(DefaultAnalyzer, field, doc.Get(field), 3);

Some Highlighter-related gotchas:

  • To highlight a field, it should be added to index with Field.Store.YES option

  • Your query should be rewritten before passing it to highlighter

  • The analyzer you pass to highlighter should be the same you use for indexing and searching