loc*_*tes 8 elasticsearch spring-data-elasticsearch
我知道elasticsearch只能在Date内部保存类型.但我可以让它知道存储/转换Java 8 ZonedDateTime,因为我在我的实体中使用此类型?
我在类路径上使用spring-boot:1.3.1 + spring-data-elasticsearch和jackson-datatype-jsr310.当我尝试保存一个ZonedDateTimenor 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));
}
}
Run Code Online (Sandbox Code Playgroud)
然后配置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();
Run Code Online (Sandbox Code Playgroud)
希望它会有所帮助。
| 归档时间: |
|
| 查看次数: |
1740 次 |
| 最近记录: |