我想对查询应用某种排序,它应该首先按单个值对所有其他值进行排序。我需要在MySQL中实现像ORDER BY CASE WHEN这样的东西,但是我找不到怎么做。
Elastic中索引中的每个元素都具有以下结构:
{
"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
}
}
}
}
首先使用值“Liverpool”对列city
进行排序,然后考虑以下示例:
{"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。
如何更改查询以获取此行为?
更新:版本为1.7.2
答案 0 :(得分:2)
您应该将"_script"用于1.7版本。试试这个:
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),请检查this doc。
答案 1 :(得分:0)
实际上你想先按城市排序然后按价格排序? 关键点是" city"提交,它的字符串(也许你设置分析?)不是整数。因此,如果您在已归档" city"上进行分析,您最好添加一个名为" raw"如果没有分析,你可以按照" city:first。排序。
尝试以下方法:
"sort": [{"city.raw": {"order": "asc"}},{"price": {"order": "asc"}}],
您可以访问https://www.elastic.co/guide/en/elasticsearch/guide/current/multi-fields.html获取更多帮助。
否则,如果你只需要制造"利物浦"城市首先是其他城市,在搜索和排序时,您应该在查询中使用提升功能。访问https://www.elastic.co/guide/en/elasticsearch/guide/2.x/multi-query-strings.html获取更多帮助。