如何在Elasticsearch中正确排序

mwecs4sa  于 2022-12-11  发布在  ElasticSearch
关注(0)|答案(1)|浏览(121)

有产品

name                       | price | company_id

product 1 of the company 1 | 10    | 1
product 2 of the company 1 | 10    | 1
product 3 of the company 1 | 20    | 1
product 4 of the company 2 | 10    | 2
product 5 of the company 2 | 10    | 2
product 6 of the company 2 | 20    | 2
product 7 of the company 3 | 10    | 3
product 8 of the company 3 | 10    | 3
product 9 of the company 3 | 20    | 3

需要按价格和公司ID排序,但公司可以交替使用
我们得到的结果是

name                       | price | company_id

product 1 of the company 1 | 10    | 1
product 4 of the company 2 | 10    | 2
product 7 of the company 3 | 10    | 3
product 2 of the company 1 | 10    | 1
product 5 of the company 2 | 10    | 2
product 8 of the company 3 | 10    | 3
product 3 of the company 1 | 20    | 1
product 6 of the company 2 | 20    | 2
product 9 of the company 3 | 20    | 3

我不知道如何正确地谷歌它,我在哪里可以看到这样的排序?

kx7yvsdv

kx7yvsdv1#

此脚本将按价格排序,然后交替使用id字段:

GET your-index/_search
{
  "sort": [
    {
      "price": {
        "order": "asc"
      }
    },
    {
      "_script": {
        "type": "number",
        "script": {
          "source": "if (doc['company_id'].value % 2 == 0) { return -1; } else { return 1; }"
        }
      }
    }
  ]
}

您可以调整脚本以按任何需要的方式排序。
有关脚本排序的详细信息:https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#script-based-sorting

相关问题