I know elasticsearch can only save Date
types internally. But can i make it aware to store/convert Java 8 ZonedDateTime
, as i use this type in my entity?
I'm using spring-boot:1.3.1 + spring-data-elasticsearch with jackson-datatype-jsr310 on the classpath. No conversions seem to apply neither when i try to save a ZonedDateTime
nor Instant
or something else.
One way of doing this is to create custom converter like this:
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 it'll help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With