Skip to main content

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

// Make a full-text search dynamic query:
// ======================================
List<Employee> employeesResults = session
// Make a dynamic query on 'Employees' collection
.Query<Employee>()
// Search for documents containing the term 'sales' in their 'Notes' field
.Search(x => x.Notes, "sales")
// Request to highlight the searched term by calling 'Highlight'
.Highlight(
x => x.Notes, // The document-field name in which we search
35, // Max length of each text fragment
4, // Max number of fragments to return per document
out Highlightings salesHighlights) // An out param for getting the highlighted text fragments
// Execute the query
.ToList();
Parameters
fieldNamestringName of a field to highlight.
fragmentLengthintMaximum length of text fragments that will be returned.
fragmentCountintMaximum number of fragments that will be returned.
fragmentsFieldstringField in returned results containing highlight fragments (mutually exclusive with 'highlightings').
highlightingsFieldHighlightingsInstance of a FieldHighlightings that contains the highlight fragments for each returned result (mutually exclusive with 'fragmentsField').
Return Value
IDocumentQueryCustomizationReturns self for easier method chaining.
FieldHighlightingsInstance of a FieldHighlightings that contains the highlight fragments for each returned result (mutually exclusive with 'fragmentsField').

Example

// Make a full-text search dynamic query:
// ======================================
List<Employee> employeesResults = await asyncSession
// Make a dynamic query on 'Employees' collection
.Query<Employee>()
// Search for documents containing the term 'sales' in their 'Notes' field
.Search(x => x.Notes, "sales")
// Request to highlight the searched term by calling 'Highlight'
.Highlight(
x => x.Notes, // The document-field name in which we search
35, // Max length of each text fragment
4, // Max number of fragments to return per document
out Highlightings salesHighlights) // An out param for getting the highlighted text fragments
// Execute the query
.ToListAsync();