Skip to content

Instantly share code, notes, and snippets.

@RyanABailey
Created March 10, 2016 21:03
Show Gist options
  • Save RyanABailey/72c510c324592fc4adb0 to your computer and use it in GitHub Desktop.
Save RyanABailey/72c510c324592fc4adb0 to your computer and use it in GitHub Desktop.
Sitecore search context highlighting
/// <summary>
/// Highlight search term
/// </summary>
/// <param name="searchTerm">Search term</param>
/// <param name="searchContent">search content</param>
/// <returns>Search content with highlighted search term</returns>
private static string HighlightSearchTerm(string searchTerm, string searchContent)
{
// create analyzer
var analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
// create FuzzyQuery using the BooleanQuery for multiple words
var booleanQuery = new BooleanQuery();
var segments = searchTerm.ToLower().Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
foreach (var segment in segments)
{
var fuzzyQuery = new FuzzyQuery(new Term("", segment), 0.7f, 3);
booleanQuery.Add(new BooleanClause(fuzzyQuery, Occur.SHOULD));
}
// create highlighter - using strong tag to highlight in this case (change as needed)
IFormatter formatter = new SimpleHTMLFormatter("<strong>", "</strong>");
// excerpt set to 200 characters in length
var fragmenter = new SimpleFragmenter(200);
var scorer = new QueryScorer(booleanQuery);
var highlighter = new Highlighter(formatter, scorer) { TextFragmenter = fragmenter };
// optional step to remove html tags from content
string rawPageContent = Sitecore.StringUtil.RemoveTags(searchContent);
// get highlighted fragment
Lucene.Net.Analysis.TokenStream stream = analyzer.TokenStream("", new StringReader(rawPageContent));
string highlightedFragment = highlighter.GetBestFragment(stream, rawPageContent);
if (highlightedFragment == null)
{
// null is returned if no matching text found
return searchContent;
}
return highlightedFragment;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment