弹性搜索按布尔字段排序

时间:2020-09-10 11:35:13

标签: elasticsearch

我想在称为 trusted 的字段中按真实值对列表进行排序。

我发现sort选项不支持布尔排序。

我该如何实现?

1 个答案:

答案 0 :(得分:2)

如果我很了解您的问题,我尝试在ES 7.8本地进行测试,并在索引中提取了以下数据:

“内容”:“这是一个测试”, “可信”:true

“内容”:“这是一个新测试”, “可信”:true

“内容”:“这不是测试”, “可信”:false

这是索引的映射:

"mappings" : {
  "properties" : {
    "content" : {
      "type" : "text",
      "fields" : {
        "keyword" : {
          "type" : "keyword",
          "ignore_above" : 256
        }
      }
    },
    "trusted" : {
      "type" : "boolean"
    }
  }
}

这是"order" : "desc"时的查询:

{
  "sort": [
    {
      "trusted": {
        "order": "desc"
      }
    }
  ]
}

响应:

"hits" : [
  {
    "_index" : "boolean-sorting",
    "_type" : "_doc",
    "_id" : "B-YleHQBsTCl1BZvrFdA",
    "_score" : null,
    "_source" : {
      "content" : "This is a test",
      "trusted" : true
    },
    "sort" : [
      1
    ]
  },
  {
    "_index" : "boolean-sorting",
    "_type" : "_doc",
    "_id" : "CeYleHQBsTCl1BZvtFdJ",
    "_score" : null,
    "_source" : {
      "content" : "This is a new test",
      "trusted" : true
    },
    "sort" : [
      1
    ]
  },
  {
    "_index" : "boolean-sorting",
    "_type" : "_doc",
    "_id" : "DOYleHQBsTCl1BZvvVfl",
    "_score" : null,
    "_source" : {
      "content" : "This is not a test",
      "trusted" : false
    },
    "sort" : [
      0
    ]
  }
]

"order":"asc"时,响应为:

"hits" : [
  {
    "_index" : "boolean-sorting",
    "_type" : "_doc",
    "_id" : "DOYleHQBsTCl1BZvvVfl",
    "_score" : null,
    "_source" : {
      "content" : "This is not a test",
      "trusted" : false
    },
    "sort" : [
      0
    ]
  },
  {
    "_index" : "boolean-sorting",
    "_type" : "_doc",
    "_id" : "B-YleHQBsTCl1BZvrFdA",
    "_score" : null,
    "_source" : {
      "content" : "This is a test",
      "trusted" : true
    },
    "sort" : [
      1
    ]
  },
  {
    "_index" : "boolean-sorting",
    "_type" : "_doc",
    "_id" : "CeYleHQBsTCl1BZvtFdJ",
    "_score" : null,
    "_source" : {
      "content" : "This is a new test",
      "trusted" : true
    },
    "sort" : [
      1
    ]
  }
]

链接: https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html

如果我回答错误,请告诉我。