0

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 Answers2

1

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

L.B
  • 114,136
  • 19
  • 178
  • 224
0

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
buru
  • 3,190
  • 25
  • 35
  • `To highlight a field, it should be added to index with Field.Store.YES option` You don't need to store if you plan to highlight an extarnal source such as original (text) file indexed. – L.B Nov 11 '11 at 16:21
  • @L.B. still, it can be a gotcha if you want to highlight document field's text and don't know about such highlighter requirement. – buru Nov 13 '11 at 15:04