首页 > 解决方案 > Elasticsearch 按不在过滤器中的字段值排序

问题描述

如果此字段不是请求中查询的一部分,有人可以帮助我进行查询,该查询将根据某些字段值对结果项进行排序。我有一个查询:

{
    "_source": [
        "ico",
        "name",
        "city",
        "status"
    ],
    "sort": {
        "_score": "desc",
        "status": "asc"
    },
    "size": 20,
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "normalized": {
                            "query": "idona",
                            "analyzer": "standard",
                            "boost": 3
                        }
                    }
                },
                {
                    "term": {
                        "normalized2": {
                            "value": "idona",
                            "boost": 2
                        }
                    }
                },
                {
                    "match": {
                        "normalized": "idona"
                    }
                }
            ]
        }
    }
}

结果根据字段状态按字母升序排序。状态包含很少的值,例如 [活动的、取消的、旧的....],我需要像提升查询中的每个可能值这样的东西。例如主动提升5,取消提升4,旧提升3......可以做到吗?谢谢。

标签: sortingelasticsearchboost

解决方案


您需要使用脚本进行自定义排序来实现您想要的。

我刚刚match_all为我的查询使用了通用查询,您可能可以继续在那里添加您的查询逻辑,但是您正在寻找的解决方案sort在下面的查询部分中。

确保这status关键字类型

基于值的自定义排序

POST <your_index_name>/_search
{  
   "query":{  
      "match_all":{  

      }
   },
   "sort":[  
      { "_score": "desc" }, 
      {  
         "_script":{  
            "type":"number",
            "script":{  
               "lang":"painless",
               "inline":"if(params.scores.containsKey(doc['status'].value)) { return params.scores[doc['status'].value];} return 100000;",
               "params":{  
                  "scores":{  
                     "active":5,
                     "old":4,
                     "cancelled":3
                  }
               }
            },
            "order":"desc"
         }
      }
   ]
}

在上面的查询中,继续添加scores查询部分中的值。例如,如果您的价值是new并且您希望它是价值2,那么您的分数将在下面:

{  
   "scores":{  
      "active":5,
      "old":4,
      "cancelled":3,
      "new":6
   }
}

所以基本上文档将首先被排序_score,然后在排序后的文档上,脚本排序将被执行。

请注意,脚本排序desc本质上是因为我知道您希望active在顶部显示文档,然后是其他值。随意玩弄它。

希望这可以帮助!


推荐阅读