10. elasticsearch 排序

1.普通排序

先按age排序再用name排序

{
  "query": {
    "match_all": {}
  }
  , 
  "sort": [
    {
      "age": { "order": "desc"},
      "name": { "order": "desc"}
    }
  ]
}

2. 数组字段排序

如果某个字段是数组,也是可以排序的,不过需要指定 mode 。mode 支持 minmaxavgsum

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"}
          }
        }
      }
    }
  }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值