Session: Querying: How to use Highlighting
Highlighting can be a great feature for increasing search UX. To take leverage of it use highlight
method.
Syntax
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);
Parameters | ||
---|---|---|
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. |
Options
private String groupKey;
private String[] preTags;
private String[] postTags;
// getters and setters
Options | ||
---|---|---|
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. |
Example
Reference<Highlightings> highlightingsRef = new Reference<>();
List<SearchItem> results = session
.query(SearchItem.class, ContentSearchIndex.class)
.highlight("text", 128, 1, highlightingsRef)
.search("text", "raven")
.toList();
StringBuilder builder = new StringBuilder();
builder.append("<ul>");
for (SearchItem result : results) {
String[] fragments = highlightingsRef.value.getFragments(result.getId());
builder.append("<li>")
.append(fragments[0])
.append("</li>");
}
builder.append("</ul>");
String ul = builder.toString();
from index 'ContentSearchIndex'
where search(text, 'raven')
include highlight(text, 128, 1)
Remarks
Note
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