use of org.opensearch.common.CheckedSupplier in project OpenSearch by opensearch-project.
the class UnifiedHighlighter method highlight.
@Override
public HighlightField highlight(FieldHighlightContext fieldContext) throws IOException {
@SuppressWarnings("unchecked") Map<String, CustomUnifiedHighlighter> cache = (Map<String, CustomUnifiedHighlighter>) fieldContext.cache.computeIfAbsent(UnifiedHighlighter.class.getName(), k -> new HashMap<>());
if (cache.containsKey(fieldContext.fieldName) == false) {
cache.put(fieldContext.fieldName, buildHighlighter(fieldContext));
}
CustomUnifiedHighlighter highlighter = cache.get(fieldContext.fieldName);
MappedFieldType fieldType = fieldContext.fieldType;
SearchHighlightContext.Field field = fieldContext.field;
FetchSubPhase.HitContext hitContext = fieldContext.hitContext;
CheckedSupplier<String, IOException> loadFieldValues = () -> {
List<Object> fieldValues = loadFieldValues(highlighter, fieldContext.context.getQueryShardContext(), fieldType, hitContext, fieldContext.forceSource);
if (fieldValues.size() == 0) {
return null;
}
return mergeFieldValues(fieldValues, MULTIVAL_SEP_CHAR);
};
Snippet[] fieldSnippets = highlighter.highlightField(hitContext.reader(), hitContext.docId(), loadFieldValues);
if (fieldSnippets == null || fieldSnippets.length == 0) {
return null;
}
List<Snippet> snippets = new ArrayList<>(fieldSnippets.length);
for (Snippet fieldSnippet : fieldSnippets) {
if (Strings.hasText(fieldSnippet.getText())) {
snippets.add(fieldSnippet);
}
}
if (snippets.isEmpty()) {
return null;
}
if (field.fieldOptions().scoreOrdered()) {
// let's sort the snippets by score if needed
CollectionUtil.introSort(snippets, (o1, o2) -> Double.compare(o2.getScore(), o1.getScore()));
}
String[] fragments = new String[snippets.size()];
for (int i = 0; i < fragments.length; i++) {
fragments[i] = snippets.get(i).getText();
}
return new HighlightField(fieldContext.fieldName, Text.convertFromStringArray(fragments));
}
Aggregations