elasticsearch解决JAVA日期型数据的导入

前几天练习使用JAVA向es导入数据,想到了日期型数据是怎么处理的。然后在网上查询了解到es日期型如果使用JAVA导入会出现8小时的时差,具体出现的原因请转到https://blog.csdn.net/linkedin_38160998/article/details/68951075或者自己百度。

网上不少的解决方式,我觉得需要自己来写一下。

第一种:使用时间戳记录时间。

存入数据时,使用String转换为date然后转换为long(这里使用String是方便格式转换):

public final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str="2016-01-25 00:00:00";
Date date=dateFormat.parse(str);
Long dateLong=date.getTime();

获取到数据后,使用long转换为date之后转换为String:

DateFormat dateFormatdateFormat=new SimpleDateFormat();
long dateLong=1453651200000L;
Date date=new Date(dateLong);
String dateStr=dateFormat.format(date);
System.out.print(dateStr);

第二种:直接使用String存入es

Date time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2016-7-21 00:00:00");
IndexResponse response = client.prepareIndex("database", "table")
     .setSource(XContentFactory.jsonBuilder().startObject()
         .field("number",0.8029)
         .field("time",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time))
     .endObject())
     .get();

总的来说,通过这两种方式存入数据后,需要再通过JAVA获取到数据后,需要进行类型的转换。

猜你喜欢

转载自blog.csdn.net/FV8023/article/details/97146077
今日推荐