Sort based on a Python List (array) and this list is not stored in the Elastic search

I would like to sort the hits in my results in a specific order and this order can be made available from a Python list or a python dictionary.

I already tried using the script fields like mentioned in Medium website( Medium) but that is also not working.

The field that i want to sort on is part of the _source and the sorting array/object is not from es and is available externally.

Hmm, could you clarify what do you want to do more or show some simple example?

There is a python client of Elasticsearch, but it only works according to its API. I didn't understand what is your trouble.

As it can be said at the moment, why the "part of the _source" is not indexed as fields in the Elasticsearch index (if then, you can sort the "hits" by the field)?

First of thanks for your reply, here is the explanation of the sort problem
I query Elasticsearch with list of document_id's let's say

"document_id": [123456, 456789,123789, 789456,789123,465132,456321]

the above field(document_id) is in already present in the es index and i get the results,

But the resulting hits doesn't have the same sort as I passed it above.

Now I want the hits to be sorted in the same order as the the original list
Original list is --> [123456, 456789,123789, 789456,789123,465132,456321]

I suppose you queried terms query to query those documents whose "document_id" field is in the list of terms.

Terms query only filter documents which match the condition. The documents are of course not aligned as the same position as the terms list and they are sorted by _score as default.

Sorting search results mainly spports descending or ascending of some fields and not supports sorting according to some list.

If you want to align the sort result, you have to use

If you are using python client and the result size is small, I recommend to sort by client side. If the result size is big, consider querying multiple times for each single term query.

Thanks alot for your reply, I used the script based sorting to solve the problem

1 Like

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