Ordering results in ElasticSearch by the order in which ids are provided

Inspired by the post https://damienalexandre.fr/post/elasticsearch-ids-query-order

I wanted to order query results in ElasticSearch by the order in which I’ve provided the ids in the query that I’ve issued. For example, If I wanted to query the documents based on their title, “apple”, “orange” and “banana” then I want the documents returned to be in order of “apple”, “orange” and “banana” irrespective of their score in ElasticSearch.

As mentioned earlier, this post has been inspired by an excellent post by Damien, which does exactly the same thing. I just wanted to do the same thing but via Java API, since I couldn’t found an straightforward answer in Java, I decided to try my own workaround.

My workaround is a bit of a hack as I am just giving positive weight to the documents in increasing order of their priority. So, if I want a document to rank higher according to their position in the query order, I am giving it the highest positive weight and the weight keeps on decreasing as the priority decreases.

For the sake of brevity, I am assuming that I’ve a TitleMapping class, which contains the title and also the rank of the title that we expect (rank 1 is the highest priority and so on).

BoolQueryBuilder qb = QueryBuilders.boolQuery()
.should(QueryBuilders.termsQuery("title",titleMappings.stream()
.map(titleMapping -> titleMapping.getTitle()).collect(Collectors.toList())));
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders
.functionScoreQuery(qb)
.maxBoost(50f)
.scoreMode("max")
.boostMode(CombineFunction.REPLACE);
for (TitleMapping titleMapping : titleMappings) {
functionScoreQueryBuilder.add(FilterBuilders.termFilter("title",
titleMapping.getFaqId()), ScoreFunctionBuilders.weightFactorFunction(50 - titleMapping.getRank()));
}
return builder.setQuery(functionScoreQueryBuilder).setSize(size).setPreference("_primary_first").execute();

So, that’s my workaround for getting documents in the same order as I’ve specified their attributes in the query.