How to store Java 8 dates (JSR-310) in elasticsearch

I know that elasticsearch can only save Date types. But can I do this to store / convert Java 8 ZonedDateTime since I use this type in my entity?

I am using spring-boot: 1.3.1 + spring -data-elasticsearch with jackson-datatype-jsr310 in the classpath. Conversions don't seem to apply either when trying to save ZonedDateTime , Instant , or anything else.

+7
spring-data-elasticsearch elasticsearch
source share
1 answer

One way to do this is to create a custom converter as follows:

 import com.google.gson.*; import java.lang.reflect.Type; import java.time.ZonedDateTime; import static java.time.format.DateTimeFormatter.*; public class ZonedDateTimeConverter implements JsonSerializer<ZonedDateTime>, JsonDeserializer<ZonedDateTime> { @Override public ZonedDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return ZonedDateTime.parse(jsonElement.getAsString(), ISO_DATE_TIME); } @Override public JsonElement serialize(ZonedDateTime zonedDateTime, Type type, JsonSerializationContext jsonSerializationContext) { return new JsonPrimitive(zonedDateTime.format(ISO_DATE_TIME)); } } 

and then configure JestClientFactory to use this converter:

  Gson gson = new GsonBuilder() .registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeConverter()).create(); JestClientFactory factory = new JestClientFactory(); factory.setHttpClientConfig(new HttpClientConfig .Builder("elastic search URL") .multiThreaded(true) .gson(gson) .build()); client = factory.getObject(); 

Hope this helps.

0
source share

All Articles