如何在Spring Data Elasticsearch中使用Instant / JodaDateTimeConverter

时间:2017-01-16 16:38:39

标签: spring-data-elasticsearch

有一个JodaDateTimeConverter类,它显然是用于存储Spring Data Elasticsearch的Instant字段。但是我该如何使用它?我还没有找到任何例子。

尝试将Instant用作日期字段:

@Field(index = FieldIndex.analyzed, type = Date)
private Instant someTime;

给了我这个例外:

Caused by: java.lang.IllegalArgumentException: unknown property [epochSecond]
    at org.elasticsearch.index.mapper.core.DateFieldMapper.innerParseCreateField(DateFieldMapper.java:520)
    at org.elasticsearch.index.mapper.core.NumberFieldMapper.parseCreateField(NumberFieldMapper.java:241)
    at org.elasticsearch.index.mapper.FieldMapper.parse(FieldMapper.java:321)
    ... 21 more

3 个答案:

答案 0 :(得分:0)

在使用存储库时考虑......

@Document(indexName = "ESINDEX", type = "TYPE", shards = 5)
public class YourClass implements java.io.Serializable {

@Id
private String url;

.
. 
.

@Field(type = FieldType.Date, format = DateFormat.date_optional_time)
private Date created;
@Field(type = FieldType.Date, format = DateFormat.date_optional_time)
private Date updated;

.
.
}

答案 1 :(得分:0)

通过使用https://github.com/spring-projects/spring-data-elasticsearch/wiki/Custom-ObjectMapper中所述的自定义对象映射器并配置Jackson将Instants序列化为时间戳,我找到了解决此问题的方法:

public class CustomEntityMapper implements EntityMapper {

private ObjectMapper objectMapper;

public CustomEntityMapper(ObjectMapper objectMapper) {
    this.objectMapper = objectMapper;
    objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    objectMapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false);
}

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

}

Spring配置代码:

    @Bean
    @Autowired
    public ElasticsearchTemplate elasticsearchTemplate(Client client) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        return new ElasticsearchTemplate(client, new CustomEntityMapper(objectMapper));
    }

答案 2 :(得分:0)

如果您使用es生成的Id,则使用此方法会中断自动Id分辨率。在此处查看我的帖子 - spring-data-elastic Id field not populated on reads when using CustomEntityMapper