我知道elasticsearch只能在内部保存 Date
类型。那么我能否让它意识到存储/转换 Java 8 的 ZonedDateTime
,因为我在实体中使用了这种类型?
我正在使用 spring-boot:1.3.1 + spring-data-elasticsearch,并且在类路径上有 jackson-datatype-jsr310。当我尝试保存 ZonedDateTime
、Instant
或其他类型时,似乎没有应用任何转换。
我知道elasticsearch只能在内部保存 Date
类型。那么我能否让它意识到存储/转换 Java 8 的 ZonedDateTime
,因为我在实体中使用了这种类型?
我正在使用 spring-boot:1.3.1 + spring-data-elasticsearch,并且在类路径上有 jackson-datatype-jsr310。当我尝试保存 ZonedDateTime
、Instant
或其他类型时,似乎没有应用任何转换。
创建自定义转换器是实现这一目标的一种方法,例如:
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));
}
}
然后配置JestClientFactory
来使用此转换器:
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();