Examples of how to get going with search result highlighting, using the Sitecore ContentSearch API and Solr
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..
Our 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.
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.
Solr 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.
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
ExtraParams, to tell Solr which highlighter to use:
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.
I’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