简体   繁体   中英

How to index document containing ZonedDateTime field in elasticsearch

I'm trying to store a document with a zonedDateTime filed in es, but i'm getting parsing error: org.elasticsearch.index.mapper.MapperParsingException: failed to parse field [creationDate] of type [date]

Here is my document definition

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

I'm getting this error:

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]

I can't figure out why I'm getting this error message.

I figure out how to do this: JavaTimeModule is not use by default byt ObjectMapper, we need to register it.

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);
     }
  }

Finally add it to ElasticsearchTemplate:

new ElasticsearchTemplate(client, new CustomEntityMapper());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM