Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 471
locobytes Avatar asked Jan 08 '16 09:01

locobytes


1 Answers

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.

like image 93
fywe Avatar answered Nov 01 '22 06:11

fywe