Highlighting is used to distinguish fragments that match keywords within search results visually.
An HTML tag surrounds highlighted fragments. Using the fluent API, you can request highlighting as part of a projection expression passed to the [Select method](🔗). To do so, invoke the `AsHighlighted
`Â extension method on a string property.
Assume you indexed instances of a `BlogPost
` class with a `Title
` and `Content
` property. Search for `BlogPost
` and retrieve the `Title
` and a highlight from the `Content
` property like this.
## Overwrite default styling
By default, highlighted keywords are wrapped in **\<em>** tags. To overwrite this styling, pass to the `AsHighlighted
` method an instance of the `HighlightSpec
` class, and set its `PreTag
` and `PostTag
` properties.
## Control fragment number and length
By default, the entire field is highlighted and retrieved. This is usually desired for shorter fields, but for longer fields, you probably want to extract one or a few fragments instead. To achieve this, set the `NumberOfFragments
` property on the `HighlightSpec
` instance.
You can also control the length of fragments by setting the `FragmentSize
` property. If you do not, the server default value of 100Â is used.
Note
Do not set the `
FragmentSize
` property to a value lower than 18.
For example, the following code retrieves a single fragment that is 200 characters long (excluding HTML tags used to wrap keywords) for the **Content** field.
## Determine concatenated fragments
If you set `NumberOfFragments
`, multiple fragments are passed from the server to a value greater than one. The fragments are automatically concatenated with a space ( ) between them. To override this, pass in a `Func<IEnumerable<string>, string>
` to the `HighlightSpec
` `Concatenation
` method.
The previous example uses an extension method that concatenates fragments and places an ellipsis (...) between each. You can perform more complex operations.
## Ensure the projected property is not empty
The projected property is an empty string if no highlights exist for the requested field. Use an if statement to ensure that the property value is not empty.
Note
If statement is executed in memory. So, in the above example, the highlight and the Title property are retrieved from the server, which means that more data is sent over the wire. That is usually not a problem, but something to be aware of.
## Highlight with typed search
_Typed search_ provides different ways to implement the highlighting and encoding of search results.
## Highlight with unified search
When using **unified search**, HTML encoding is enabled by default for the **Title** and **Excerpt** fields. The text is encoded before the HTML tags that surround highlighted content are added. You can turn off default HTML encoding; see [Unified Search](🔗).