————————————————
版权声明:本文为CSDN博主「CTO修炼手册」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Prepared/article/details/102893852

在使用 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"
		}
	}
}
/**
 * 计算早晚高峰流量
 * @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


 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐