首页 > 解决方案 > 弹性搜索按布尔字段排序

问题描述

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

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

我怎样才能做到这一点?

标签: elasticsearch

解决方案


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

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

"content": "这是一个新的测试", "trusted": true

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

这是索引的映射:

"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

请让我知道如果我回答错误,我很乐意提供帮助。


推荐阅读