Last active
May 31, 2022 05:25
-
-
Save darklow/7132077 to your computer and use it in GitHub Desktop.
ElasticSearch custom sort, based on provided ids array order.
Original code from here: http://damienalexandre.fr/post/elasticsearch-ids-query-order
Rewritten to new "function_score" syntax
Note: You need to remove \n new lines from "script" field in order to get it work.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
q = { | |
"query": { | |
"function_score": { | |
"boost_mode": "replace", | |
"query": { | |
"ids": { | |
"values": [ | |
50, | |
80, | |
44, | |
12 | |
] | |
} | |
}, | |
"script_score": { | |
"params": { | |
"ids": [ | |
50, | |
80, | |
44, | |
12 | |
] | |
}, | |
"script": """ | |
count = ids.size(); | |
id = org.elasticsearch.index.mapper.Uid.idFromUid(doc['_uid'].value); | |
for (i = 0; i < count; i++) { | |
if (id == ids[i]) { return count - i; } | |
}""", | |
} | |
} | |
}, | |
"size": 20, | |
"from": 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't work in my case.
I update it to:
hope it helps someone