Using Solr to highlight search results
This topic is valid for Sitecore 9.0 and later.
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)
The Solr documentation provides more details.
Solr configuration
You do not need any configuration to enable highlighting in Solr.
Example
This example shows how you use the Solr highlighting feature in Sitecore code:
protected void OnClick(object sender, EventArgs e)
{
var index = ContentSearchManager.GetIndex("sitecore_master_index");
var highlightField = "_name";
using (var context = index.CreateSearchContext())
{
var results = context.Query<SearchResultItem>(string.Format("_name:{0}", this.txtName.Text), new QueryOptions()
{
Highlight = new HighlightingParameters
{
Fields = new[]
{
highlightField
},
BeforeTerm = "<span class='highlight'>",
AfterTerm = "</span>"
}
});
if (results != null)
{
foreach (var result in results)
{
result[string.Format("highlight{0}", highlightField)] = string.Join(", ", results.Highlights[result["_uniqueid"].ToString()].Snippets[highlightField].ToArray());
}
}
this.rptResults.DataSource = results;
this.rptResults.DataBind();
}
}
Best practices
It is best practice to specify the parameter that you use for highlighting. You only need to set the h1
and h1.fl
parameters to get results.
These are the most commonly used parameters.
Parameter |
Default |
Description |
---|---|---|
hl |
false |
Use this parameter to enable or disable highlighting. |
hl.method |
Original |
The highlighting implementation to use. Acceptable values are: |
hl.fl |
|
Specifies a list of fields to highlight. This accepts a comma- or space-delimited list of fields for which Solr should generate highlighted snippets. A wildcard of ‘*’ (asterisk) can be used to match field globs, such as ‘text_*’, or even ‘*’ to highlight on all fields where highlighting is possible. When using ‘*’, consider adding |