问题描述: 在ElasticSearch中的时间格式是 yyyy-MM-dd'T'HH:mm:ss 的格式的,但是在使用Jest查询结果时 执行jestClient.execute(search)
,会提示错误:
com.google.gson.JsonSyntaxException: 2018-09-30T16:07:53...Caused by: java.text.ParseException: Failed to parse date ["2018-09-30T16:07:53"]: No time zone indicator at com.google.gson.internal.bind.util.ISO8601Utils.parse(ISO8601Utils.java:274) ~[gson-2.8.5.jar:na] at com.google.gson.DefaultDateTypeAdapter.deserializeToDate(DefaultDateTypeAdapter.java:149) ~[gson-2.8.5.jar:na] ... 48 common frames omitted
可以看到错误时Gson的错误,我们数据的格式和Jest去查询的格式不相符所致
看源码在io.searchbox.client.AbstractJestClient#ELASTIC_SEARCH_DATE_FORMAT
中定义了 public static final String ELASTIC_SEARCH_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";
与我们的数据格式不相符,因此需要去定义Gson的格式
解决方案: 将JestClient自己实现并加入spring的管理中,问题得到解决
/** * @author qi.liu * @create 2018-10-18 15:14 * @desc 描述: **/@Configurationpublic class JestClientConfig { @Autowired(required = false) private JestClientFactory jestClientFactory; @Autowired private ElasticsearchJestProperties properties; @Bean public JestClient createJestClient() { GsonFactoryBean gsonFactoryBean = new GsonFactoryBean(); gsonFactoryBean.setDateFormatPattern("yyyy-MM-dd'T'HH:mm:ss"); gsonFactoryBean.afterPropertiesSet(); HttpClientConfig.Builder builder = new HttpClientConfig.Builder(properties.getUri()).gson(gsonFactoryBean.getObject()) .maxTotalConnection(properties.getMaxTotalConnection()) .defaultMaxTotalConnectionPerRoute(properties.getDefaultMaxTotalConnectionPerRoute()) .readTimeout(properties.getReadTimeout()) .multiThreaded(properties.getMultiThreaded()); JestClientFactory factory = jestClientFactory != null ? jestClientFactory : new JestClientFactory(); factory.setHttpClientConfig(builder.build()); return factory.getObject(); }}
时间被正确解析出来: