DEBUG.WIKI
ZgoCloud:多地区部署,按需选节点;日本、美国、香港、德国
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS
晚安云;香港 CN2 ¥15/月

解决 Elasticsearch 报错 MapperParsingException 日期解析异常

分析写入 Elasticsearch 提示 failed to parse field of type date 的时间格式不兼容根因,提供 format 模板扩展方案。

问题现象

向 Elasticsearch 写入文档时被拒绝:

{
  "error": {
    "root_cause": [
      {
        "type": "mapper_parsing_exception",
        "reason": "failed to parse field [created_at] of type [date] in document with id '1001'. Preview of field's value: '2026/11/15 16:30:00'"
      }
    ],
    "type": "mapper_parsing_exception",
    "reason": "failed to parse field [created_at] of type [date] in document with id '1001'. Preview of field's value: '2026/11/15 16:30:00'",
    "caused_by": {
      "type": "illegal_argument_exception",
      "reason": "failed to parse date field [2026/11/15 16:30:00] with format [strict_date_optional_time||epoch_millis]"
    }
  },
  "status": 400
}

触发根因

  1. 目标索引的 Mapping 将该字段声明为 date 类型,默认只支持 ISO 8601 标准格式(如 2026-11-15T16:30:00Z)或毫秒时间戳。
  2. 业务端传入了自定义的斜杠或空格格式(如 yyyy/MM/dd HH:mm:ss),无法被默认解析器解析。

解决步骤与操作命令

步骤一:在 Mapping 中配置多模式日期格式(多格式并存)

在创建索引或索引模板时,声明允许匹配多种时间格式:

PUT my_index
{
  "mappings": {
    "properties": {
      "created_at": {
        "type": "date",
        "format": "yyyy-MM-dd HH:mm:ss||yyyy/MM/dd HH:mm:ss||strict_date_optional_time||epoch_millis"
      }
    }
  }
}

步骤二:业务客户端序列化统一采用 ISO 8601 标准

在 Jackson 或 FastJson 中统一格式化为标准 UTC ISO 字符串:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone = "UTC")
private Date createdAt;

验证确认

再次写入此前被拒的数据:

curl -X POST "http://localhost:9200/my_index/_doc/1001" -H 'Content-Type: application/json' -d '{"created_at": "2026/11/15 16:30:00"}'

成功返回 {"result": "created"},日期解析错误彻底解决。