elasticsearch学习笔记(二十九)——Elasticsearch 将一个field索引两次来解决字符串排序问题
下面描述一个场景如果某个字段的类型是text在创建索引的时候针对每个document对应的这个text字段都会对内容进行分词。由于ES不允许对已经存在的field的类型进行修改就会导致该字段一直都是会被分词那么如果之后有需求想对该字段排序就不行了。具体看下面展示的示例。PUT /test_index { mappings: { properties: { field1: { type: text } } } } GET /test_index/_search { query: { match_all: {} }, sort: [ { field1: { order: desc } } ] } { error: { root_cause: [ { type: illegal_argument_exception, reason: Fielddata is disabled on text fields by default. Set fielddatatrue on [field1] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead. } ], type: search_phase_execution_exception, reason: all shards failed, phase: query, grouped: true, failed_shards: [ { shard: 0, index: test_index, node: P-b-TEvyQOylMyEcMEhApQ, reason: { type: illegal_argument_exception, reason: Fielddata is disabled on text fields by default. Set fielddatatrue on [field1] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead. } } ], caused_by: { type: illegal_argument_exception, reason: Fielddata is disabled on text fields by default. Set fielddatatrue on [field1] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead., caused_by: { type: illegal_argument_exception, reason: Fielddata is disabled on text fields by default. Set fielddatatrue on [field1] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory. Alternatively use a keyword field instead. } } }, status: 400 }这个时候要想解决这个问题就可以将一个string field建立两次索引一个分词用来搜索一个不分词用来进行排序。Alternatively use a keyword field instead.根据错误中的提示我们重新建立索引PUT /test_index { mappings: { properties: { field1: { type: text, fields: { keyword: { type: keyword } } } } } } GET /test_index/_search { query: { match_all: {} }, sort: [ { field1.keyword: { order: desc } } ]

相关新闻