2016-01-08 13 views
6

So che elasticsearch può salvare solo i tipi Date internamente. Ma posso renderlo consapevole di memorizzare/convertire Java 8 ZonedDateTime, come io uso questo tipo nella mia entità?Come memorizzare le date di Java 8 (JSR-310) in elasticsearch

Sto usando spring-boot: 1.3.1 + spring-data-elasticsearch con jackson-datatype-jsr310 sul classpath. Nessuna conversione sembra applicarsi né quando provo a salvare uno ZonedDateTime né su un altro Instant.

risposta

0

Un modo per farlo è quello di creare convertitore personalizzato come questo:

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)); 
    } 
} 

e quindi configurare JestClientFactory per utilizzare questo convertitore:

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(); 

Spero che ti aiuto.

+0

Il mio male, mi dispiace. Ho pensato che ISO_DATE_FORMAT non ha informazioni sulla zona. Rimuoverò il commento errato. – mindas