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 | ||
---|---|---|
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
// 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();