Custom sorting with an Elasticsearch query?

I have some documents indexed on Elasticsearch, looking like these samples:

{'id': 1, 'user_group_id': 1, 'is_popular': false, 'added_at': '2020-10-05T10:27:59.214Z'}
{'id': 2, 'user_group_id': 2, 'is_popular': false, 'added_at': '2020-10-05T10:27:59.214Z'}
{'id': 3, 'user_group_id': 1, 'is_popular': false, 'added_at': '2020-10-10T10:27:59.214Z'}
{'id': 4, 'user_group_id': 2, 'is_popular': false, 'added_at': '2020-10-15T10:27:59.214Z'}
{'id': 5, 'user_group_id': 1, 'is_popular': false, 'added_at': '2020-10-15T10:27:59.214Z'}
{'id': 6, 'user_group_id': 2, 'is_popular': true, 'added_at': '2020-10-15T10:27:59.214Z'}
{'id': 7, 'user_group_id': 2, 'is_popular': true, 'added_at': '2020-10-15T10:27:59.214Z'}

I want to build a query that gets top 2 users have user_group_id = 1 and descending to added_at date time on top and then all users have is_popular = true and descending to added_at date time and then added_at date time in descending order user.

So, for the examples shown above, the results would be something like:

{'id': 5, 'user_group_id': 1, 'is_popular': false, 'added_at': '2020-10-15T10:27:59.214Z'}
{'id': 3, 'user_group_id': 1, 'is_popular': false, 'added_at': '2020-10-10T10:27:59.214Z'}
{'id': 6, 'user_group_id': 2, 'is_popular': true, 'added_at': '2020-10-15T10:27:59.214Z'}
{'id': 7, 'user_group_id': 2, 'is_popular': true, 'added_at': '2020-10-15T10:27:59.214Z'}
{'id': 4, 'user_group_id': 2, 'is_popular': false, 'added_at': '2020-10-15T10:27:59.214Z'}
{'id': 2, 'user_group_id': 2, 'is_popular': false, 'added_at': '2020-10-05T10:27:59.214Z'}
{'id': 1, 'user_group_id': 1, 'is_popular': false, 'added_at': '2020-10-05T10:27:59.214Z'}

Is it possible in Elasticsearch?

I don't think you can produce exactly that output.

You can do:

top 2 users have user_group_id = 1 and descending to added_at date time on top

Using

all users have is_popular = true and descending to added_at date time

You can use a term query and sort on added_at.

added_at date time in descending order user

I guess you want to exclude the previous results so I'd probably use a bool query with a must_not clause to exclude is_popular = true or just filter using again a term query on is_popular with value false.
And sort again as saw previously.

Is it possible in Elasticsearch?

I don't think it's doable with one single request. Which means that you probably will have to assemble the results yourself on the client side.

This could help may be:

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.