sorting - 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......可以做到吗?谢谢。
解决方案
您需要使用脚本进行自定义排序来实现您想要的。
我刚刚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
在顶部显示文档,然后是其他值。随意玩弄它。
希望这可以帮助!
推荐阅读
- javascript - Uncaught (in promise) DOMException: Unable to decode audio data from pyAudio to JavaScript
- javascript - REST API - 连接困难
- sql - SQL Server:每个月为行,每年为列
- java - 如何在 AmazonS3 和 AWSSecretManager 的代理参数中配置 ClientConfiguration
- angular - 根据特定条件禁用角度工具提示
- excel - VBIDE.CodeModule.DeleteLines 程序不工作
- javascript - 显示元素不会将其放回父元素内
- python - 无法导入波形 (EOFError)
- windows - 笔记本电脑在 ubuntu 上收费,但在 windows 10 上不收费
- python - 如何使用python相对于matplotlib中的一行进行文本旋转?