How to make Spring Data Elasticsearch work with java.time.LocalDateTime for date

前端 未结 2 939
你的背包
你的背包 2020-12-28 21:12

I am using Spring Data support for Elasticsearch. Here is the timestamp field mapping:

@Field(type = FieldType.Date, index = FieldIndex.not_analyzed, store =         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-28 21:31

    Check https://github.com/spring-projects/spring-data-elasticsearch/wiki/Custom-ObjectMapper to add JavaTimeModule to your ObjectMapper.

    @Configuration
    public class ElasticSearchConfiguration {
    
      @Bean
      public ElasticsearchTemplate elasticsearchTemplate(Client client) {
        return new ElasticsearchTemplate(client, new CustomEntityMapper());
      }
    
      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 mapToObject(String source, Class clazz) throws IOException {
          return objectMapper.readValue(source, clazz);
        }
      }
    }
    

提交回复
热议问题