背景說明
最近在做一個 Elasticsearch 的分頁查詢,並且對查詢結果按照特定字段進行排序的功能。
但是執行結果卻報錯,報錯信息如下:
{ "error": { "root_cause": [ { "type": "illegal_argument_exception", "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [state] 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": "alarm", "node": "hdLJanxRTbmF52eK6-FFgg", "reason": { "type": "illegal_argument_exception", "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [state] 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 }
原因分析
查詢語句如下:

GET alarm/_search // index為 alarm { "query" : { "bool" : { "must" : [ { "match_phrase" : { "state" : { "query" : "confirmed", "slop" : 0, "boost" : 1.0 } } } ], "disable_coord" : false, "adjust_pure_negative" : true, "boost" : 1.0 } }, "from": 1, // 分頁,第幾頁開始 "size": 5, // 分頁,每頁顯示多少條 "sort": { // 排序,按照 state 字段降序排序 "state": { "order": "desc" } } }
測試分析:
1)去除排序語句,分頁查詢是OK的,問題出在了排序字段;
2)按照 integer 類型 或者 date 類型的字段排序都是OK的,但是 string 類型排序報錯(示例中的state字段為 string 類型)
解決方案
其實在報錯信息里已經提供了解決方案:
需要對 string類型的字段,單獨設置加載到內存中,才能排序。
Set fielddata=true on [state] in order to load fielddata in memory by uninverting the inverted index.
具體設置操作如下:
PUT alarm/_mapping/alarmInfoHistory/ { "properties":{ "state":{ "type":"text", "fielddata":true } } }
執行結果:
{ "acknowledged": true }
再次執行排序查詢查詢語句,就OK了。
Good Luck~
PS:
如果想按照多個字段排序(按照 state 和 alarmGrade 降序排序),SQL參考如下:
{ "query":{ "bool":{ "must":[ { "match_phrase":{ "state":{ "query":"confirmed", "slop":0, "boost":1 } } } ], "disable_coord":false, "adjust_pure_negative":true, "boost":1 } }, "from":1, "size":10, "sort":[ { "state":{ "order":"desc" } }, { "alarmGrade":{ "order":"desc" } } ] }