1.普通排序
先按age排序再用name排序
{
"query": {
"match_all": {}
}
,
"sort": [
{
"age": { "order": "desc"},
"name": { "order": "desc"}
}
]
}
2. 数组字段排序
如果某个字段是数组,也是可以排序的,不过需要指定 mode 。mode 支持 min、max、avg、sum。
PUT student
{
"mappings" : {
"properties" : {
"name" : {
"type" : "keyword"
},
"score" : {
"type" : "integer"
}
}
}
}
# 添加文档
POST _bulk
{ "index" : { "_index" : "student", "_id" : "1" } }
{ "name" : "张三", "score": [80, 90]}
{ "index" : { "_index" : "student", "_id" : "2" } }
{ "name" : "李四", "score": [78, 95] }
按照 score 的最小值排序:
{
"query": {
"match_all": {}
},
"sort": [
{
"score": {"order" : "asc", "mode": "min"}
}
]
}
3.字符排序
被解析的字符串字段也是多值字段, 但是很少会按照你想要的方式进行排序。如果你想分析一个字符串,如 fine old art , 这包含 3 项。我们很可能想要按第一项的字母排序,然后按第二项的字母排序,诸如此类,但是 Elasticsearch 在排序过程中没有这样的信息。
你可以使用 min 和 max 排序模式(默认是 min ),但是这会导致排序以 art 或是 old ,任何一个都不是所希望的。
为了以字符串字段进行排序,这个字段应仅包含一项: 整个 not_analyzed 字符串。 但是我们仍需要 analyzed 字段,这样才能以全文进行查询
一个简单的方法是用两种方式对同一个字符串进行索引,这将在文档中包括两个字段: analyzed 用于搜索, not_analyzed 用于排序
"tweet": {
"type": "string",
"analyzer": "english",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
}
tweet 主字段与之前的一样: 是一个 analyzed 全文字段。
新的 tweet.raw 子字段是 not_analyzed.
{
"query": {
"match": {
"tweet": "elasticsearch"
}
},
"sort": "tweet.raw"
}
4. 聚合后进行排序
{
"query": {
"match_phrase": {
"goods_name_simple": "工具"
}
},
"size":0,
"aggs":{
"group_by_spuid":{
"terms":{
"field": "goods_commonid",
"order" : [
{"avg_goods_price":"desc"},
{ "top_hit":"desc"}
]
},
"aggs":{
"avg_goods_price":{
"avg":{
"field":"goods_price"
}
},
"top_hit" : {
"max": {
"script": {"source": "_score"}
}
}
}
}
}
}
本文详细讲解了Elasticsearch中的排序策略,包括按年龄和姓名混合排序、数组字段的min/max排序、字符串字段排序以及聚合后排序实例。了解如何在实际场景中灵活运用这些技术进行高效搜索和数据组织。
1664

被折叠的 条评论
为什么被折叠?



