Session: Querying: How to use highlighting?
Highlighting can be a great feature for increasing search UX. To take leverage of it use Highlight
method which is a part of query customizations available from Customize
.
Syntax
IDocumentQueryCustomization Highlight(
string fieldName,
int fragmentLength,
int fragmentCount,
string fragmentsField);
IDocumentQueryCustomization Highlight(
string fieldName,
int fragmentLength,
int fragmentCount,
out FieldHighlightings highlightings);
Parameters |
|
|
fieldName |
string |
Name of a field to highlight. |
fragmentLength |
int |
Maximum length of text fragments that will be returned. |
fragmentCount |
int |
Maximum number of fragments that will be returned. |
fragmentsField |
string |
Field in returned results containing highlight fragments (mutually exclusive with 'highlightings'). |
highlightings |
FieldHighlightings |
Instance of a FieldHighlightings that contains the highlight fragments for each returned result (mutually exclusive with 'fragmentsField'). |
Return Value |
|
IDocumentQueryCustomization |
Returns self for easier method chaining. |
FieldHighlightings |
Instance of a FieldHighlightings that contains the highlight fragments for each returned result (mutually exclusive with 'fragmentsField'). |
Example
FieldHighlightings highlightings = null;
SearchItem[] results = session
.Query<SearchItem>("ContentSearchIndex")
.Customize(x => x.Highlight("Text", 128, 1, out highlightings))
.Search(x => x.Text, "raven")
.ToArray();
StringBuilder builder = new StringBuilder()
.AppendLine("<ul>");
foreach (SearchItem result in results)
{
string[] fragments = highlightings.GetFragments(result.Id);
builder.AppendLine(string.Format("<li>{0}</li>", fragments.First()));
}
string ul = builder
.AppendLine("</ul>")
.ToString();