使用elastic search执行聚合aggregations操作时报错Fielddata is disabled on text fields by default错误,具体信息如下

{
  "error": {
    "root_cause": [
      {
        "type": "illegal_argument_exception",
        "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [interests] 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": "megacorp",
        "node": "pUI1S7JwQpSp6-P0wHJRbQ",
        "reason": {
          "type": "illegal_argument_exception",
          "reason": "Fielddata is disabled on text fields by default. Set fielddata=true on [interests] 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 fielddata=true on [interests] 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 fielddata=true on [interests] 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
}

官网解释为ES5.0Fielddata is disabled on text fields by default意思是默认禁用Fielddata,原因是加载fielddata是一个昂贵的过程,可能会导致用户遇到延迟命中。

有两种解决方案:

  1. 字段加上关键字keyword(推荐),代码如下:

    GET /megacorp/employee/_search
    {
     "query": {
       "match": {
         "last_name": "Smith"
       }
     },
     "aggs": {
       "all_interests": {
         "terms": { "field": "interests.keyword" }
       }
     }
    }
  2. 在聚合前发送指令开启fielddata,指令如下:

    PUT megacorp/_mapping/employee/
    {
     "properties": {
       "interests": { 
         "type":     "text",
         "fielddata": true
       }
     }
    }

happy coding!