Sitecore Search Highlighting with Solr - the highlights
#
In this postExamples of how to get going with search result highlighting, using the Sitecore ContentSearch API and Solr
#
What does highlighting look like?Solrâs highlighting system is extremely powerful. A simple use-case is to show the part of the document which matched a userâs search terms. We call this part a snippet. We can even supply some HTML to wrap the matching terms:
Search: healthy Wrap with: Snippet: The healthy workplace toolkits support you either as a health care employer..
#
Code: A Basic SearchOur documents have a field called âSummaryâ. Sitecore and the ContentSearch API donât know about this field by default, so we create a custom SearchResultItem class to include the field in our search results:
Letâs search for any documents with the word healthy in the Summary field. Note that highlighting is currently only supported when we search directly through SolrNet, so weâll construct the query that way.
#
Code: Letâs add highlighting!We populate a QueryOptions
object with a HighlightingParameters
configuration, and pass this in when creating our query. We specify (Field) the field to include in the highlight snippet returned by Solr, (BeforeTer
) the token to place before our matched terms, and (AfterTerm
) the token to place after the matched terms.
Now, letâs execute our query, passing in the queryOptions
object. The results object we get back now contains a populated Highlights collection.
#
Controlling the size of the snippetSolr allow us to pass in a parameter, Fragsize
, to control the length of the snippet returned to us. I recommend playing around with this to suit your needs.
#
A choice of highlighters!Solr supports different highlighters â take a look at the âChoosing a Highlighterâ section in the Solr documentation: https://lucene.apache.org/solr/guide/6_6/highlighting.html
The newest, shiniest highlighter (which shipped with Solr 6.4) is the Unified Highlighter (https://lucene.apache.org/solr/guide/6_6/highlighting.html#Highlighting-TheUnifiedHighlighter). By using this highlighter instead, we can remove the Fragsize
parameter and instead get back a whole sentance, containing our highlighted terms. We have to add another parameter to the QueryOptions
object, ExtraParams
, to tell Solr which highlighter to use:
#
Can I use Linq?To make use of the QueryOptions
object, we have to query directly through SolrNet. Losing our fancy ContentSearch Linq capabilities is a big deal! Hereâs a not-so-great workaround to get it back. We serialize the Linq query to a string, then use it to create a native SolrNet query, attaching our QueryOptions once again.
#
FeedbackIâd love to hear nicer ways of working with Linq and Highlighting â please let me know any work youâve done in this area!
Full gist of this functionality here: https://gist.github.com/christofur/178b3a8ff93d6a899c00b15dcdd49966