In our Elasticsearch highlevel client based code we have some code that uses the BucketOrder.key(...)
and BucketOrder.count(...)
factory methods.
What are equivalent constructs for the the elasticsearch-java client SDK? The code now requires a NamedValue<SortOrder>
. What should be used for the names in case of?:
Bucket.Order.key(true)
BucketOrder.count(false)
Original helper function using highlevel client code:
TermsAggregation.Builder buildAggregation(final AggregatePair aggregatePair) {
final var aggregation = new TermsAggregation.Builder()
.terms(aggregatePair.aggregateName())
.field(aggregatePair.aggregateField())
.size(aggregatePair.size());
// BucketOrder.key enables the sortering by name; true configures ascending sort by alphabet.
// BucketOrder.count enables the sortering by count, false configures descending sort by count.
if ("key".equals(aggregatePair.getOrder())) {
aggregation.order(BucketOrder.key(true));
} else {
aggregation.order(BucketOrder.count(false));
}
return aggregation;
}
New helper function:
private @NotNull NamedValue<SortOrder> toSortOrder(final @NotNull AggregatePair aggregatePair) {
if ("key".equals(aggregatePair.order())){
return NamedValue.of("???", SortOrder.Asc);
}else{
return NamedValue.of("???", SortOrder.Desc);
}
}
Context of building converting objects to aggregations:
private @NotNull Map<String, Aggregation> toAggregations(final @Nullable List<AggregatePair> aggregations) {
if (null == aggregations) {
return Collections.emptyMap();
}
return aggregations
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toMap(AggregatePair::aggregateName,
aggregatePair ->
new Aggregation.Builder()
.terms( termsAggreationBuilder -> termsAggreationBuilder
.field(aggregatePair.aggregateField())
.size(aggregatePair.size())
.order(List.of(toSortOrder(aggregatePair))))
.build()
));
}
Context of Creating a SearchRequest
with aggregations (Work In Progress):
public @NotNull SearchRequest createRequest(final @NotNull SearchRequestParameters parameters,
final @NotNull List<String> aliases) {
if (aliases.isEmpty()) {
throw new IllegalArgumentException("aliases must not be empty");
}
final var searchRequestBuilder = new SearchRequest.Builder()
.index(aliases)
.from(parameters.from())
.size(parameters.size())
.terminateAfter(parameters.terminateAfter())
.sort(toSortOptions(parameters.sorting()))
.indicesBoost(toIndicesBoost(parameters.boostedIndexList()))
.highlight(createHighlightBuilder().build());
//TODO: add more query configuration and the query itself.
final var searchParameters = parameters.searchParameters();
if(searchParameters != null) {
searchRequestBuilder.aggregations(toAggregations(searchParameters.aggregatedFields()));
}
return searchRequestBuilder.build();
}