Elasticsearch solves the import of JAVA date data

A few days ago, I practiced using JAVA to import data to es, and I thought of how to deal with date data. Then I searched online and learned that if the es date type is imported using JAVA, there will be an 8-hour time difference. For the specific reason, please go to https://blog.csdn.net/linkedin_38160998/article/details/68951075 or Baidu yourself.

There are many solutions on the Internet, I think I need to write it myself.

The first: use a timestamp to record the time.

When storing data, use String to convert to date and then to long (here, String is used to facilitate format conversion):

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

After obtaining the data, use long to convert to date and then convert to String:

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

The second type: directly use String to save into 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();

In general, after storing data through these two methods, you need to obtain the data through JAVA, and then you need to perform type conversion.

Guess you like

Origin blog.csdn.net/FV8023/article/details/97146077