How to add multiple fields for sorting top hits in ElasticSearch Java API?

Viewed 993

I know that ES supports sorting top hits by more than one fields, like sort: ["_score", "datetime"] suggested by this post: https://discuss.elastic.co/t/top-hits-query-with-same-score/107018

But how to do it using Java API?

The AggregationBuilders.topHits().sort() only receives one field as parameter.

Should I use enter image description here and SortBuilder as parameter?

If so, SortBuilder asks for a QueryShardContext parameter, which I don't know how to create. I have never used it before. None of the other requests uses this QueryShardContext.

Is there any simple way to do it, like, just pass in an array of fields into sort()?

Thanks in advance!

1 Answers

There are overloaded TopHitsAggregationBuilder.sort() methods, namely one that takes String name, i.e. the name of a field, so you can do it like this:

TopHitsAggregationBuilder thabuilder = AggregationBuilders.topHits("top");
thabuilder.sort("datetime", SortOrder.DESC);
thabuilder.sort("field2", SortOrder.ASC);
...

All the sort calls will add a new sort component to the top-hits aggregation.

Related