Elasticsearch按某个字段值的顺序排列 [英] Elasticsearch order by a certain field value first
问题描述
我想对查询进行某种排序,它应该首先按单个值对我的文档进行排序,然后再对所有其他值进行排序.我需要在MySQL中实现类似ORDER BY CASE WHEN的功能,但是我找不到如何做到这一点的方法.
I'd like to apply a certain sort to a query, it should sort my documents by a single value first then all the others. I need to achieve something like the ORDER BY CASE WHEN in MySQL, but I couldn't find how to do it.
Elastic索引中的每个元素都具有以下结构:
Each element in the index in Elastic has the following structure:
{
"id": 123,
"name": "Title",
"categories": ["A", "B", "C"],
"price": 100,
"city": "London",
"country": "United Kingdom",
"status": 1
}
我执行以下查询:
{
"fields": [],
"sort": [{"price": {"order": "asc"}}],
"size": 0,
"query": {
"query_string": {
"query": "status:1 AND country:'United Kingdom'"
}
},
"aggs": {
"id": {
"terms": {
"field": "id",
"size": 10
}
}
}
}
因此,首先对值 city
列进行排序,并考虑以下示例:
So by sorting the column city
with value "Liverpool" first and considering the following example:
{"id": 1, "name": "Test", "categories": ["A", "B", "C"], "price": 100, "city": "London", "country": "United Kingdom", "status": 1 }
{"id": 2, "name": "Sample", "categories": ["A", "D", "F"], "price": 200, "city": "Manchester", "country": "United Kingdom", "status": 1 }
{"id": 3, "name": "Title", "categories": ["X", "Y", "Z"], "price": 1000, "city": "Liverpool", "country": "United Kingdom", "status": 1 }
我希望将以下ID作为输出:3、1、2.
I expect to have as output the following id: 3, 1, 2.
如何更改查询以获取此行为?
How can I change my query to obtain this behaviour?
更新:版本为1.7.2
UPDATE: The version is 1.7.2
推荐答案
您应该使用 for 1.7版本.试试这个:
You should use "_script" for 1.7 version. Try this:
1.7:
"query" : {
....
},
"sort" : {
"_script" : {
"script" : "doc['city'].value == 'Liverpool' ? 1 : 0",
"type" : "number",
"order" : "desc"
},
"example_other_field_order":"asc",
"next_example_field_order":"asc"
}
有关Elasticsearch的最新版本(> = 5.5),请检查此文档.
For latest version of elasticsearch (>= 5.5) check this doc.
这篇关于Elasticsearch按某个字段值的顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!