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

public IDocumentQueryCustomization highlight(String fieldName, int fragmentLength, int fragmentCount, String fragmentsField);

public IDocumentQueryCustomization highlight(String fieldName, int fragmentLength, int fragmentCount, Reference<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

QHowToUseHighlighting_SearchItem s = QHowToUseHighlighting_SearchItem.searchItem;
Reference<FieldHighlightings> highlightingsRef = new Reference<>();
List<SearchItem> results = session
  .query(SearchItem.class, "ContentSearchIndex")
  .customize(new DocumentQueryCustomizationFactory().highlight("Text", 128, 1, highlightingsRef))
  .search(s.text, "raven")
  .toList();

StringBuilder builder = new StringBuilder();
builder.append("<ul>");

for (SearchItem result : results) {
  String[] fragments = highlightingsRef.value.getFragments(result.getId());
  builder.append("<li>" + fragments[0] + "</li>");
}
builder.append("</ul>");

String ul = builder.toString();