欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ElasticSearch41:初识搜索引擎_上机动手实战如何定制搜索结果的排序规则

程序员文章站 2022-07-05 14:22:13
...
1.默认排序规则
默认情况下,是按照_score降序排序的,然后在某些情况下,如filter,不计算_score,所以没有可用的_score

例子:
GET /test_index/test_type/_search
{
  "query": {
    "bool": {
      "filter": {
        "term": {
          "test_field": "hello"
        }
      }
    }
    
  }
}
执行结果:
{
  "took": 33,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 0,
    "max_score": null,
    "hits": []
  }
}



当然,还有constant_score
GET /test_index/test_type/_search
{
  "query": {
    "constant_score": {
      "filter": {
        "term": {
          "test_field": "hello"
        }
      }
    }
  }    
}
执行结果:
{
  "took": 3,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 0,
    "max_score": null,
    "hits": []
  }
}

2.定制排序规则
例子:查询10到50岁的员工,并按照join_date正序排序
GET /company/employee/_search
{
  "query": {
    "range": {
      "age": {
        "gte": 10,
        "lte": 50
      }
    }
  },
  "sort": [
    {
      "join_date": "asc"
    }
  ]
}

执行结果:

{
  "took": 565,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 3,
    "max_score": null,
    "hits": [
      {
        "_index": "company",
        "_type": "employee",
        "_id": "1",
        "_score": null,
        "_source": {
          "address": {
            "province": "zhejiang",
            "city": "wenzhou",
            "country": "china"
          },
          "name": "tom",
          "age": 31,
          "join_date": "2015-01-02"
        },
        "sort": [
          1420156800000
        ]
      },
      {
        "_index": "company",
        "_type": "employee",
        "_id": "2",
        "_score": null,
        "_source": {
          "address": {
            "province": "zhejiang",
            "city": "hangzhou",
            "country": "china"
          },
          "name": "jerry",
          "age": 25,
          "join_date": "2017-01-02"
        },
        "sort": [
          1483315200000
        ]
      },
      {
        "_index": "company",
        "_type": "employee",
        "_id": "3",
        "_score": null,
        "_source": {
          "address": {
            "province": "zhejiang",
            "city": "ningbo",
            "country": "china"
          },
          "name": "tiny",
          "age": 18,
          "join_date": "2018-01-02"
        },
        "sort": [
          1514851200000
        ]
      }
    ]
  }
}


相关标签: elasticsearch