Provide order of ids and retrieve docs in the provided order

I have I have order of ids, [1, 4, 2, 5] and some filters { match: {...} } and I want the resulting documents to be returned in the order [1, 4, 2, 5]. What would be the best way to achieve this?

Sample document:

    "id": <uuid>,
    "name": "Some name",
    "description": "Some description"

Now I am aware that ES stores _id for each document and _id for es doc and id field inside my doc are same.

So I want to provide array of ids and get the results in that order after all the filtering.

For example I have 4 documents

    "id": "abcd",
    "name": "test1",
    "description": "test1"
    "id": "bcde",
    "name": "test2",
    "description": "test2"
    "id": "cdef",
    "name": "test3",
    "description": "test3"

now i have array of ids ["cdef", "abcd", "bcde"] so I want to query es and get results in the above specified order meaning doc with cdef has to be first in the hits then doc with abcd and then doc with bcde

Elasticsearch will not guarantee the order like that, you can only do sorts.

Yes by default ES won't guarantee that but is there a way using using custom function for sorting? I found some snippets using painless script but not sure from docs how can I achieve behavior I want?

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