Springdata Elasticsearch 使用 LocalDateTime 配置

关于在Springdata Elasticsearch 使用 LocalDateTime 的配置(base on Springdata Elasticsearch 3.2)

索引实体

	 /**
     * 访问日期
     */
    @Field(type = FieldType.Date)
    private LocalDateTime dateTime;

配置文件

/**
 * @author Ming
 * @date 2020/9/26 14:10
 */
@Configuration
public class ElasticsearchConfiguration extends ElasticsearchConfigurationSupport {

    @Bean
    @Override
    public EntityMapper entityMapper() {
        ElasticsearchEntityMapper entityMapper = new ElasticsearchEntityMapper(elasticsearchMappingContext(),null);
        entityMapper.setConversions(elasticsearchCustomConversions());
        return entityMapper;
    }

    /**
     * conversions for LocalDateTime
     * @return
     */
    @Bean
    @Override
    public ElasticsearchCustomConversions elasticsearchCustomConversions() {
        List<Converter> converters= new ArrayList<>();
        converters.add(DateToLocalDateTimeConverter.INSTANCE);
        converters.add(LongToLocalDateTimeConverter.INSTANCE);
        return new ElasticsearchCustomConversions(converters);
    }

    @ReadingConverter
    enum LongToLocalDateTimeConverter implements Converter<Long, LocalDateTime> {

        INSTANCE;

        @Override
        public java.time.LocalDateTime convert(Long source) {
            return Instant.ofEpochMilli(source).atZone(ZoneId.systemDefault()).toLocalDateTime();
        }
    }

    @WritingConverter
    enum DateToLocalDateTimeConverter implements Converter<Date, LocalDateTime> {

        INSTANCE;

        @Override
        public LocalDateTime convert(Date date) {
            Instant instant = date.toInstant();
            return instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
        }
    }


}

你可能感兴趣的:(java,spring,es)