如何在elasticsearch中存储Java 8 (JSR-310)日期

8

我知道elasticsearch只能在内部保存 Date 类型。那么我能否让它意识到存储/转换 Java 8 的 ZonedDateTime,因为我在实体中使用了这种类型?

我正在使用 spring-boot:1.3.1 + spring-data-elasticsearch,并且在类路径上有 jackson-datatype-jsr310。当我尝试保存 ZonedDateTimeInstant 或其他类型时,似乎没有应用任何转换。

1个回答

2

创建自定义转换器是实现这一目标的一种方法,例如:

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

希望这能有所帮助。

我的错,抱歉。我以为ISO_DATE_FORMAT没有区域信息。我会删除错误的注释。 - mindas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接