Session: Querying: How to use Highlighting

Highlighting can be a great feature for increasing search UX. To take leverage of it use highlight method.


IDocumentQuery<T> highlight(String fieldName,
                            int fragmentLength,
                            int fragmentCount,
                            Reference<Highlightings> highlightings);

IDocumentQuery<T> highlight(String fieldName,
                            int fragmentLength,
                            int fragmentCount,
                            HighlightingOptions options,
                            Reference<Highlightings> highlightings);
fieldName string Name of a field to highlight.
path string Path to 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.
options HighlightingOptions Options that can be used for customization.
highlightings Highlightings Instance of a Highlightings that contains the highlight fragments for each returned result.


private String groupKey;
private String[] preTags;
private String[] postTags;

// getters and setters
groupKey string Grouping key for the results. If null results are grouped by document ID (default).
preTags string[] Array of pre tags used when highlighting.
postTags string[] Array of post tags used when highlighting.


Reference<Highlightings> highlightingsRef = new Reference<>();
List<SearchItem> results = session
    .query(SearchItem.class, ContentSearchIndex.class)
    .highlight("text", 128, 1, highlightingsRef)
    .search("text", "raven")

StringBuilder builder = new StringBuilder();

for (SearchItem result : results) {
    String[] fragments = highlightingsRef.value.getFragments(result.getId());

String ul = builder.toString();
from index 'ContentSearchIndex'
where search(text, 'raven')
include highlight(text, 128, 1)



Default <b></b> tags are coloured and colours are returned in following order:

  •  yellow,
  •  lawngreen,
  •  aquamarine,
  •  magenta,
  •  palegreen,
  •  coral,
  •  wheat,
  •  khaki,
  •  lime,
  •  deepskyblue,
  •  deeppink,
  •  salmon,
  •  peachpuff,
  •  violet,
  •  mediumpurple,
  •  palegoldenrod,
  •  darkkhaki,
  •  springgreen,
  •  turquoise,
  •  powderblue