io.polyglotted.elastic.search.ResultBuilder Maven / Gradle / Ivy
package io.polyglotted.elastic.search;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import io.polyglotted.common.model.MapResult;
import io.polyglotted.common.util.ListBuilder.ImmutableListBuilder;
import io.polyglotted.common.util.MapBuilder;
import io.polyglotted.common.util.MapRetriever;
import io.polyglotted.elastic.common.MetaFields;
import io.polyglotted.elastic.common.Verbose;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import java.util.List;
import java.util.Map;
import static io.polyglotted.common.model.MapResult.simpleResult;
import static io.polyglotted.common.util.CollUtil.filterKeys;
import static io.polyglotted.common.util.ListBuilder.immutableListBuilder;
import static io.polyglotted.elastic.common.MetaFields.HIGHLTGHT_FIELD;
import static io.polyglotted.elastic.common.MetaFields.ID_FIELD;
import static io.polyglotted.elastic.search.SearchUtil.hitSource;
@SuppressWarnings("unused")
public interface ResultBuilder extends ResponseBuilder {
default List buildFrom(SearchResponse response, Verbose verbose) {
ImmutableListBuilder builder = immutableListBuilder();
for (SearchHit hit : response.getHits()) { builder.add(buildFromHit(hit, verbose)); }
return builder.build();
}
default T buildFromHit(SearchHit hit, Verbose verbose) {
T result = buildVerbose(hitSource(hit), verbose);
Map highlightFields = hit.getHighlightFields();
if (result instanceof MapResult && !highlightFields.isEmpty()) {
Multimap highlight = ArrayListMultimap.create();
for (Map.Entry entry : highlightFields.entrySet()) {
HighlightField field = entry.getValue();
for (Text frag : field.fragments()) { highlight.put(field.name(), frag.string()); }
}
MapResult.class.cast(result).put(HIGHLTGHT_FIELD, highlight.asMap());
}
return result;
}
default T buildVerbose(MapResult source, Verbose verbose) {
if (source == null || source.isEmpty()) return null;
return verbose.buildFrom(source, buildResult(source));
}
T buildResult(MapResult source);
ResultBuilder> NullBuilder = MapBuilder::immutableMap;
ResultBuilder HeaderBuilder = MetaFields::readHeader;
ResultBuilder IdBuilder = (source) -> MapRetriever.reqdStr(source, ID_FIELD);
ResultBuilder EmptyBuilder = source -> simpleResult();
ResultBuilder SimpleBuilder = source -> source;
ResultBuilder SourceBuilder = (source) -> simpleResult(filterKeys(source, MetaFields::isNotMeta));
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy