Trying to figure out how to sort elasticsearch results so that fields with specific values always show first. In this case, I want specific SKUs to show first when showing category pages (I'm using bool query to generate elasticsearch results for category pages).
If I were trying to accomplish this with MySQL, I'd use the case statement:
ORDER BY CASE sku
WHEN 'sku1' then 1 WHEN 'sku2' then 2 WHEN 'sku3' then 3 ELSE 4 END
This query executes:
{
"sort" : [
{
"_script": {
"type": "number",
"script": {
"inline" : "params.sortOrder.indexOf(doc['skuid_text'].value)",
"params": {
"sortOrder": [
"SKUID1",
"SKUID2",
"SKUID3"
]
}
},
"order": "asc"
}
}
],
"query" :{
"bool" : {
"must" : [
{
"term" : {
"category_codes" : "CATEGORY1"
}
}
]
}
}
}
But it's returning "-1" as the sort value for all records, eg:
sort": [
-1
]
Note: 'skuid_text' is the SKU field I have analyzed as "keyword" type. I have tried both doc['skuid_text'].value and doc['skuid_text'] And I have verified that SKUs in the "sortOrder" array are definitely included in the result set.
What am I missing? Or, is there a completely different way to approach the problem?
答案 0 :(得分:0)
实际上原始查询有点工作,只是我用“asc”命令的方式是将sortOrder数组中的所有skus推到最后。
如果你在sortOrder中反转skus的顺序并对其进行一些数学计算,它将正确排序。虽然有点hack-y。我很想知道是否有更好的方式让人想到。
{
"sort" : [
{
"_script": {
"type": "number",
"script": {
"inline" : "(9999)-params.sortOrder.indexOf(doc['skuid_text'].value)",
"params": {
"sortOrder": [
"SKUID3",
"SKUID2",
"SKUID1"
]
}
},
"order": "asc"
}
}
],
"query" :{
"bool" : {
"must" : [
{
"term" : {
"category_codes" : "CATEGORY1"
}
}
]
}
}
}
答案 1 :(得分:0)
这个插件完成了< 5版本所需的功能。您可以按原样尝试安装,或者查看作者对5.x更新的评价。
https://github.com/jprante/elasticsearch-functionscore-conditionalboost