Add highlighting to a custom search type
Solr's highlighting feature lets you include fragments in the highlighting section of a query response.
You can add highlights to a custom search type by first enabling highlighting on a specific field, then adding the Highlights type property to the custom search type.
To add highlights:
-
In the
<SOLR_DIR>\server\solr\<SOLR_CORE_NAME>\conffolder, in themanaged-schemafile, enable highlighting for the desired fields by setting thestoredproperty of the fields totrue, as shown in the following example:RequestResponse<field name="title_t" type="text_general" multiValued="true" indexed="true" stored="true"/> <field name="text" type="text_general" multiValued="true" indexed="true" stored="true"/> -
Create a custom search type class and add public properties that return the
Highlightstype, then map each property to its appropriate index field, as shown in the following example:RequestResponsepublic class SimpleHighlightResultItem { [IgnoreIndexField] public string Title { get; set; } [IndexField("title")] public Highlights HighlightsInTitle { get; set; } [IgnoreIndexField] public string Text { get; set; } [IndexField("text")] public Highlights HighlightsInText { get; set; } } -
Use the custom search type in a LINQ query. For example:
RequestResponsevar index = ContentSearchManager.GetIndex("sitecore_master_index"); using (var context = index.CreateSearchContext()) { var result = context.GetQueryable<SimpleHighlightResultItem>() .Where(it => it.Title == "Sitecore" && it.Text == "customer experience") .WithHighlights(hl => hl.HighlightOn(i => i.HighlightsInText)); foreach (var resultItem in result) { string[] highlightSegments = resultItem.HighlightsInText.ToArray(); } }The preceding LINQ query generates the following Solr query:
q=(title_t:("Sitecore") AND text:("customer experience")) ... &hl=true&hl.fl=textThe
highlightSegmentsproperty contains the following segment:RequestResponse" complexity that has previously held marketers back, the latest version of <em>Sitecore</em> makes <em>customer</em> <em>experience</em>"
Highlight multiple fields in a LINQ query
You can get highlighted matches for several index fields in a single LINQ query.
The following query returns highlights for both the title and text index fields:
var result = context.GetQueryable<SimpleHighlightResultItem>()
.Where(it => it.Title == "Sitecore" && it.Text == "customer experience")
.WithHighlights(hl => hl
.HighlightOn(i => i.HighlightsInText)
.HighlightOn(i => i.HighlightsInTitle)
)
.ToArray();The preceding LINQ query generates the following Solr query: q=(title_t:("Sitecore") AND text:("customer experience")) ... &hl=true&hl.fl=title_t,text
The HighlightsInText property contains the following segment:
" complexity that has previously held marketers back, the latest version of <em>Sitecore</em> makes <em>customer</em> <em>experience</em>"The HighlightsInTitle property contains the following segment:
"<em>Sitecore<em> Experience Platform"