我需要构建 flex 搜索查询,并按数组中的字段值定位进行排序。
与MySQL类似:
SELECT * FROM `comments` ORDER BY FIELD(`id`,'17','3','5','12') DESC, id DESC;
或Postgres:SELECT * FROM comments
LEFT JOIN unnest('{12,5,3,17}'::int[]) WITH ORDINALITY t(id, ord) USING (id) ORDER BY t.ord, id DESC;
最佳答案
您正在寻找Elasticsearch中的自定义排序
可以通过轻松的脚本来实现
这是我的工作
PUT my_test
{
"mappings": {
"properties": {
"animal": {
"type": "keyword"
}
}
}
}
填充文档POST my_test/_doc
{
"animal": "mouse"
}
POST my_test/_doc
{
"animal": "cat"
}
POST my_test/_doc
{
"animal": "dog"
}
自定义排序GET my_test/_search
{
"query": {
"match_all": {}
},
"sort": {
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": "if(params.scores.containsKey(doc['animal'].value)) { return params.scores[doc['animal'].value];} return 100000;",
"params": {
"scores": {
"dog": 0,
"cat": 1,
"mouse": 2
}
}
},
"order": "asc"
}
}
}
关于elasticsearch - 按IN值列表位置排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62661258/