一、需求
ES中的记录只有具体时间的字段格式,需求是按日期以及其他字段嵌套聚合。
二、方法
1、ES自带的date_histogram
2、用script脚本。
三、具体解释
1、 使用date_histogram方式
(1)参数
"interval"的值赋为"day"
"format"的值赋为 "yyyy-MM-dd"
(2)结果
key_as_string:日期
key:key_as_string从1970年1月1日0时至今经历的毫秒数,所以这个值/1000/3600/24得到天数可以用在方式二。
2、 使用script
(1)代码
"script": {
"source": '''
Calendar c = Calendar.getInstance();
c.set(1970, 1 - 1, 1, 0, 0, 0);##注意月份是1-1,Calendar类的month从0开始
c.add(Calendar.DATE, (int)(doc['startTime'].value / 1000 / 3600 / 24));##加上经过的天数
Date date = c.getTime();
String format = new SimpleDateFormat('YYYY-MM-dd').format(date);
return format + ',' + doc['content.RegistrationNo.keyword'].value + ',' + doc['content.RegistrationNoColor.keyword'].value + ',' + doc['eventTypeCode.keyword'].value '''
}
"aggs": {
"result": {
"terms": {
"script": {
"source":'''
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sd = sdf.format(new Date(doc['content.FT_AlarmTime'].value));
return sd+','+doc['content.RegistrationNo.keyword'].value +','+ doc['content.RegistrationNoColor.keyword'].value'''
},
"size":1000000
}
}
}
(2)kibana结果
3、python中应用
def func(index):
query_json={
"size": 0,
"aggs": {
"result": {
"terms": {
"script": {
"source":'''
Calendar c = Calendar.getInstance();
c.set(1970,1-1,1,0,0,0);
c.add(Calendar.DATE,(int)(doc['startTime'].value/1000/3600/24));
Date date = c.getTime();
String format = new SimpleDateFormat('YYYY-MM-dd').format(date);
return format+','+doc['content.RegistrationNo.keyword'].value +','+ doc['content.RegistrationNoColor.keyword'].value +','+doc['eventTypeCode.keyword'].value'''
},"size":1000000
}
}
}
}
query = ESconn.search(index=index, body=query_json, request_timeout=360)
data=query['aggregations']['result']['buckets']
return data