在学习es时,我在查询条件中加入的字段,当排序字段时_id时可以查询出数据,但是当排序字段是 name属性时就返回错误了。
{
"query":{
"bool":{
"must":{
"exists":{
"field":"describe"
}
}
}
},
"sort":{
"name":{
"order":"asc"
}
},
"from":0,
"size":5
}
错误信息如下:
{
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted index. Note that this can use significant memory."
}
],
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"phase": "query",
"grouped": true,
"failed_shards": [
{
"shard": 0,
"index": "customer",
"node": "eP_GuuI3SZepIz2i00y4KQ",
"reason": {
"type": "illegal_argument_exception",
"reason": "Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted index. Note that this can use significant memory."
}
}
],
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted index. Note that this can use significant memory.",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Text fields are not optimised for operations that require per-document field data like aggregations and sorting, so these operations are disabled by default. Please use a keyword field instead. Alternatively, set fielddata=true on [name] in order to load field data by uninverting the inverted index. Note that this can use significant memory."
}
}
},
"status": 400
}
我的理解是,es中,针对sort和aggs操作,没有对文本内容进行提前的优化,(我觉得是类似于数据库的建立索引,不知道对不对),所以这个操作默认是不被允许的,可以通过对字段name设置 fielddata=true来实现(可能是在查询时再排序)。但是这样做会很消耗内存。所以不建议设置。
如果一定要设置,可以参考如下办法:
PUT {indexname}/_mapping/{typeName} 在es7.后面的版本,为 PUT {indexname}/_mapping
{
"properties": {
"你的字段": {
"type": "text或keyWord",
"fielddata": true
}
}
}
修改报错中提到的字段类型,修改为 text 或 keyWord。以 name 字段为例:
PUT customer/_mapping
{
"properties": {
"name": {
"type": "text",
"fielddata": true
}
}
}