需求:根据时间范围,查询es中的数据
说明:在使用logstash将关系型数据库中的数据抽到es中时,需要转为时间搓格式保存,这样就可以根据时间搓进行时间范围查询了
注意:如果不对时间字段做处理,默认的保存格式不方便进行时间范围查询
默认保存到es中的时间格式:
这种格式不方便我们的客户端进行时间范围查询
logstash抽取mysql中的数据时,对于datetime类型的字段,可以使用unix_timestamp()函数:
示例:unix_timestamp(a.create_time
) create_time
查看es中保存的时间搓数据:
java客户端查询关键代码:
将字符串时间yyyy-MM-dd HH:mm:ss转为es查询的时间搓格式
/**
* 获取时间搓
*
* @param source
* @param pattern
* @return
*/
public static long getTimestamp(String source, String pattern) {
try {
pattern = (pattern == null) ? DATE_TIME : pattern;
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
long time = dateFormat.parse(source).getTime();
return time;
} catch (ParseException e) {
LOGGER.error("时间解析失败", e);
}
throw new BusinessException("时间解析失败");
}
public static String getEsStringTimestamp(String source, String pattern) {
if (StringUtils.isBlank(source)) {
return null;
}
long timestamp = getTimestamp(source, pattern);
String esTimestamp = String.valueOf(timestamp);
return esTimestamp.substring(0, esTimestamp.length() - 3);
}
es客户端查询关键代码:
默认是 <= 和>=
// 根据时间范围查询
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("gmt_create");
rangeQueryBuilder.from("1575946364");
rangeQueryBuilder.to("1575979688");