Elasticsearch实战——搜索排序

Elasticsearch实战——搜索排序

1. 默认排序

ES是按照查询和文档的相关度进行排序的。默认按评分降序排序,搜索title字段中包含自行车关键词的文档:

GET website/_search
{
    
    
    "query":{
    
    
        "match_phrase":{
    
    
            "title":"自行车"
        }
    }
}

等价于

GET website/_search
{
    
    
  "query": {
    
    
    "match_phrase": {
    
    
      "title": "自行车"
    }
  },
  "sort": [
    {
    
    
      "_score": {
    
    
        "order": "desc"
      }
    }
  ]
}

对于match_all而言,由于只返回所有文档,不需要评分,文档的顺序为添加文档的顺序。如果需要改变match_all query的文档顺序,可以对_doc进行排序。例如返回最后添加的那条文档,可以对_doc降序排序,设置返回的文档条数为1,命令如下:

GET website/_search
{
    
    
  "size": 1,
  "query": {
    
    
    "match_all": {
    
    }
  },
  "sort": [
    {
    
    
      "_doc": {
    
    
        "order": "desc"
      }
    }
  ]
}

2. 多字段排序

ES还支持多字段排序,如下:先按照评分降序,在按照时间降序。

GET website/_search
{
    
    
  "query": {
    
    
    "match_phrase": {
    
    
      "title": "自行车"
    }
  },
  "sort": [
    {
    
    
      "_score": {
    
    
        "order": "desc"
      }
    },
    {
    
    
      "indexAt": {
    
    
        "order": "desc"
      }
    }
  ]
}

3. 距离排序

查询天津附近500km之内的城市,并按距离天津的距离升序排序:

{
    
    
  "query": {
    
    
    "bool": {
    
    
      "must": {
    
    
        "match_all": {
    
    }
      },
      "filter": {
    
    
        "geo_distance": {
    
    
          "distance": "500km",
          "location": {
    
    
            "lat": "38.993443",
            "lon": "117.158558"
          }
        }
      }
    }
  },
  "sort": [
    {
    
    
      "_geo_distance": {
    
    
        "location": {
    
    
          "lat": "38.993443",
          "lon": "117.158558"
        },
        "unit": "km"
      }
    }
  ]
}

4. 关注我

搜索微信公众号:java架构强者之路
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/dwjf321/article/details/103961662