ES-script-查询7点到9点的数据
ES 版本
6.2.4
在使用 ES 进行统计的时候,经常会用到查询某个小时的统计数据,比如统计每个小时的数据;比如计算早晚高峰的数据。
这些场景都可以使用 script 进行查询、统计。
ES 语句
{
"query": {
"bool": {
"filter": [{
"range": {
"datetime": {
"from": "2019-10-01 00:00:00",
"to": "2019-11-01 12:00:00",
"include_lower": true,
"include_upper": true,
"boost": 1.0
}
}
}, {
"script": {
"script": {
"source": "(doc['datetime'].value.hourOfDay)>=17",
"lang": "painless"
},
"boost": 1.0
}
}, {
"script": {
"script": {
"source": "(doc['datetime'].value.hourOfDay)<19",
"lang": "painless"
},
"boost": 1.0
}
}, {
"exists": {
"field": "linkdirname",
"boost": 1.0
}
}],
"adjust_pure_negative": true,
"boost": 1.0
}
},
"sort": [{
"datetime": {
"order": "desc"
}
}],
"aggregations": {
"sum_volume": {
"sum": {
"field": "volume"
}
}
}
}
java 代码
/**
* 计算早晚高峰流量
* @param startDate
* @param endDate
* @param volume_max
* @param startHour
* @param endHour
* @param sumId
* @return
*/
private int computeMorningAndEveningPeak(String startDate, String endDate, SumAggregationBuilder volume_max,
int startHour, int endHour, String sumId, String comField) throws ParseException {
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
boolQueryBuilder.filter(QueryBuilders.rangeQuery("datetime").gte(startDate).lte(endDate));
boolQueryBuilder.filter(QueryBuilders.scriptQuery(new Script("(doc['datetime'].value.hourOfDay)>=" + startHour)));
boolQueryBuilder.filter(QueryBuilders.scriptQuery(new Script("(doc['datetime'].value.hourOfDay)<" + endHour)));
boolQueryBuilder.filter(QueryBuilders.existsQuery(comField));
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.aggregation(volume_max).sort("datetime", SortOrder.DESC);
// 查询ES
SearchResponse response = ElasticsearchUtil.search(restHighLevelClient, sourceBuilder, ES_FLOW_5MIN, ES_DATA);
return getSumFlowByResponse(response, sumId);
}
这个属性能取哪些值,取决于 org.joda.time.MutableDateTime,有需要的可以查看源码。
- mills
- Chronology
- Zone
- ZoneRetainFields
- Year
- Weekyear
- MonthOfYear
- WeekOfWeekyear
- DayOfYear
- DayOfMonth
- DayOfWeek
- HourOfDay
- MinuteOfHour
- SecondOfDay
- SecondOfMinute
- MillisOfDay
- MillisOfSecond
等等
所有发生在我们身上的事件都是一个经过仔细包装的礼物。只要我们愿意面对它有时候有点丑恶的包装,带着耐心和勇气一点一点的拆开包装的话,我们会惊喜的看到里面珍藏的礼物。
----遇见未知的自己