2

我的弹性字段名称为“Amit 111”、“Amit 111”、“Amit 222”。

我正在尝试使用以下方法对其进行排序:

   searchSourceBuilder.query(query).sort("name.keyword", SortOrder.ASC)

它返回结果为:“Amit 111”、“Amit 222”、“Amit 111”

但我希望结果为:“Amit 111”、“Amit 111”、“Amit 222”

请帮忙。

4

2 回答 2

2

另一种方法是使用字段数据作为text您可以应用排序的字段,有关链接 URL 的更多详细信息。

您需要更改索引映射的 Java 代码,如 java 代码后所示。

searchSourceBuilder.query(query).sort("name", SortOrder.ASC)

在字段上启用字段数据创建name索引

{
  "mappings": {
    "properties": {
      "name": { 
        "type": "text",
        "fielddata": true
        }
      }
    }
  }

索引示例文档

{
  "name" : "amit 111"
}

{
  "name" : "Amit 111"
}

{
  "name" : "Amit 222"
}

您的搜索查询与name字段排序

{
    "sort": [
        {
            "name": "asc"
        }
    ]
}

结果

 "hits": [
      {
        "_index": "key",
        "_type": "_doc",
        "_id": "1",
        "_score": null,
        "_source": {
          "name": "amit 111"
        },
        "sort": [
          "111"
        ]
      },
      {
        "_index": "key",
        "_type": "_doc",
        "_id": "2",
        "_score": null,
        "_source": {
          "name": "Amit 111"
        },
        "sort": [
          "111"
        ]
      },
      {
        "_index": "key",
        "_type": "_doc",
        "_id": "3",
        "_score": null,
        "_source": {
          "name": "Amit 222"
        },
        "sort": [
          "222"
        ]
      }
    ]
于 2020-05-26T07:15:02.687 回答
1

关键字字段按原样存储,因此关键字字段的排序区分大小写。带有小写过滤器的规范器可用于索引关键字字段。

关键字字段的规范化属性类似于分析器,只是它保证分析链产生单个标记。

映射:

{
  "settings": {
    "analysis": {
      "normalizer": {
        "my_normalizer": {
          "type": "custom",
          "filter": [
            "lowercase"
          ]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "normalizer": "my_normalizer"
          }
        }
      }
    }
  }
}

查询: name.keyword 上的排序和 name.keyword 上的术语查询都将不区分大小写

{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "name.keyword": {
        "order": "asc"
      }
    }
  ]
}

结果:

"hits" : [
      {
        "_index" : "index84",
        "_type" : "_doc",
        "_id" : "SBvLT3IB8mx5yKbJQ7EC",
        "_score" : null,
        "_source" : {
          "name" : "Amit 111"
        },
        "sort" : [
          "amit 111"
        ]
      },
      {
        "_index" : "index84",
        "_type" : "_doc",
        "_id" : "SRvLT3IB8mx5yKbJULFl",
        "_score" : null,
        "_source" : {
          "name" : "amit 111"
        },
        "sort" : [
          "amit 111"
        ]
      },
      {
        "_index" : "index84",
        "_type" : "_doc",
        "_id" : "ShvLT3IB8mx5yKbJaLFg",
        "_score" : null,
        "_source" : {
          "name" : "Amit 222"
        },
        "sort" : [
          "amit 222"
        ]
      }
    ]
于 2020-05-26T07:07:59.600 回答