Highlight Search Results

“Solr has a highlighting feature. This means that Solr returns fragment of the documents that match a query in the query response. Solr includes these fragments in a special section of the response that is called the highlighting section. Solr also includes formatting clues that you use to determine how you present these fragments (or snippets)” from documentation.

  • Environment: Sitecore 9 update 1, and Solr 6.6.2.
  • References: As this is Solr specific feature, we need to refer following assemblies from our project.
    • SolrNet.dll
    • Sitecore.ContentSearch.dll
    • Sitecore.ContentSearch.SolrProvider.dll
    • Sitecore.ContentSearch.SolrNetExtension.dll
  • Solr Configuration: No configuration is required to enable this feature.

For demo purpose, i have created a book template, and added couple of book items. I have a description field on book template, which is used for highlighting search results.

Highlighter:

To show Highlight search result, created Highlighter content item, and added Highlighter component (Controller Rendering) from the presentation details. (to main placeholder)

Following points, you can observe in the below code,

  • Passing search text through query string.
  • Using HighlightingParameters to pass field name, on which highlighting should run.
  • Passing query and queryoptions to IProviderSearchContext.Query() method.

Basic Layout code: (Basic.cshtml)

@using Sitecore.Mvc
<!doctype html>
<html>
<head>
<title>Sitecore Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div>
<div>
@Html.Sitecore().Placeholder("top")
</div>
<div>
@Html.Sitecore().Placeholder("main")
</div>
<div>
@Html.Sitecore().Placeholder("bottom")
</div>
</div>
</body>
</html>
view raw basic.cshtml hosted with ❤ by GitHub

Highlighter component – Controller Rendering: (HighlighterController.cs)

using SC9SolrDemo.Models;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.SearchTypes;
using Sitecore.ContentSearch.SolrProvider.SolrNetIntegration;
using SolrNet;
using SolrNet.Commands.Parameters;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace SC9SolrDemo.Controllers
{
public class HighlighterController: Controller
{
public ActionResult Index()
{
string searchField = "description_t";
string searchValue = Request.QueryString["text"] ?? string.Empty;
if (string.IsNullOrEmpty(searchValue))
return View();
var queryOptions = new QueryOptions
{
Highlight = new HighlightingParameters
{
Fields = new[] { searchField },
BeforeTerm = "<em style='color:red'>",
AfterTerm = "</em>",
Fragsize =10000
}
};
var indexName = string.Format("sitecore_{0}_index", Sitecore.Context.Database.Name);
var index = ContentSearchManager.GetIndex(indexName);
List<HighlightResult> highlightResults = new List<HighlightResult>();
using (var context = index.CreateSearchContext())
{
var results = context.Query<SearchResultItem>(
new SolrQueryByField(searchField, searchValue), queryOptions);
foreach (var result in results)
{
var highlights = results.Highlights[result.Fields["_uniqueid"].ToString()];
if (highlights.Any())
{
foreach(var highlightResult in highlights)
{
highlightResults.Add(
new HighlightResult
{
Name = result.Name,
Value = string.Join(",", highlightResult.Value)
});
}
}
}
}
return View(highlightResults);
}
}
}

View Model (HighlightResult.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SC9SolrDemo.Models
{
public class HighlightResult
{
public string Name { get; set; }
public string Value { get; set; }
}
}
view raw HighlightResult.cs hosted with ❤ by GitHub

View (Index.cshtml)

@model IEnumerable<SC9SolrDemo.Models.HighlightResult>
@if (Model != null)
{
<ul>
@foreach (var highlight in Model)
{
<li>
<h1>
@highlight.Name
</h1>
</li>
<li>
<h3>
@Html.Raw(highlight.Value)
</h3>
</li>
}
</ul>
}
view raw Index.cshtml hosted with ❤ by GitHub

Result:

Whole source code, with Sitecore items is present at https://github.com/gopigujjula/Sitecore9SolrDemo

Note: this code is only demo purposes

References:

Happy Learning 🙂