Elasticsearch combat-search sorting

Elasticsearch combat-search sorting

1. Default sort

ES is sorted according to the relevance of queries and documents. By default, it is sorted in descending order by score, and searches 自行车for documents containing keywords in the title field :

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

Equivalent to

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

For match_all, since only all documents are returned, no scoring is required, and the order of the documents is the order of adding documents. If you need to change the document order of match_all query, you can _docsort them. For example, to return the last document added, you can _docsort in descending order and set the number of returned documents to 1. The command is as follows:

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

2. Multi-field sorting

ES also supports multi-field sorting, as follows: first in descending order by score, and then in descending order by time.

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

3. Distance sort

Query cities within 500km of Tianjin and sort them in ascending order of distance from Tianjin:

{
    
    
  "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. Follow me

Search WeChat public account: the road to a strong java architecture
Insert picture description here

Guess you like

Origin blog.csdn.net/dwjf321/article/details/103961662