如何在elasticsearch中索引包含ZonedDateTime字段的文档

时间:2019-05-03 06:51:17

标签: java elasticsearch spring-data-elasticsearch zoneddatetime

我正在尝试存储具有在es中归档的zonedDateTime的文档,但是我遇到了解析错误: org.elasticsearch.index.mapper.MapperParsingException:无法解析类型为[date]的字段[creationDate]

这是我的文档定义

@Document(indexName = "index", type = "myType")
public class myDocument {
  @Id
  private String id;
  private String text;
  @Field(type = FieldType.Date)
  private ZonedDateTime creationDate;
....

我收到此错误:

org.elasticsearch.index.mapper.MapperParsingException: failed to parse field [creationDate] of type [date]
    at org.elasticsearch.index.mapper.FieldMapper.parse(FieldMapper.java:301) ~[elasticsearch-6.4.3.jar:6.4.3]
    at org.elasticsearch.index.mapper.DocumentParser.parseObjectOrField(DocumentParser.java:482) ~[elasticsearch-6.4.3.jar:6.4.3]
    at org.elasticsearch.index.mapper.DocumentParser.parseObject(DocumentParser.java:499) ~[elasticsearch-6.4.3.jar:6.4.3]
...
Caused by: java.lang.IllegalStateException: Can't get text on a START_OBJECT at 1:509
    at org.elasticsearch.common.xcontent.json.JsonXContentParser.text(JsonXContentParser.java:86) ~[elasticsearch-x-content-6.4.3.jar:6.4.3]
    at org.elasticsearch.common.xcontent.support.AbstractXContentParser.textOrNull(AbstractXContentParser.java:269) ~[elasticsearch-x-content-6.4.3.jar:6.4.3]
    at org.elasticsearch.index.mapper.DateFieldMapper.parseCreateField(DateFieldMapper.java:444) ~[elasticsearch-6.4.3.jar:6.4.3]
    at org.elasticsearch.index.mapper.FieldMapper.parse(FieldMapper.java:295) ~[elasticsearch-6.4.3.jar:6.4.3]

我不知道为什么收到此错误消息。

1 个答案:

答案 0 :(得分:0)

我弄清楚该怎么做: JavaTimeModule默认不使用byt ObjectMapper,我们需要注册它。

public static class CustomEntityMapper implements EntityMapper {

     private final ObjectMapper objectMapper;

     public CustomEntityMapper() {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        objectMapper.registerModule(new CustomGeoModule());
        objectMapper.registerModule(new JavaTimeModule());
     }

     @Override
     public String mapToString(Object object) throws IOException {
        return objectMapper.writeValueAsString(object);
     }

     @Override
     public <T> T mapToObject(String source, Class<T> clazz) throws IOException {
        return objectMapper.readValue(source, clazz);
     }
  }

最后将其添加到ElasticsearchTemplate:

new ElasticsearchTemplate(client, new CustomEntityMapper());