索引mapping:
{
"mappings" : {
"properties" : {
"createDate" : {
"type" : "long"
},
"goodsCode" : {
"type" : "keyword"
},
"id" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"orderNumber" : {
"type" : "keyword"
},
"payDate" : {
"type" : "long"
},
"saleQty" : {
"type" : "double"
}
}
}
}
需求:
根据今年以来的销售数据,统计一天中销售的高峰时间段。
{
"query": {
"range": {
"payDate": {
"gte": 1704038400000
}
}
},
"size":0,
"aggs": {
"hours_sales":{
"terms": {
"script": {
"source": """
DateTimeFormatter df = DateTimeFormatter.ofPattern("HH").withZone(ZoneId.systemDefault());
return df.format(Instant.ofEpochMilli(doc['payDate'].value));
""",
"lang":"painless"
},
"size": 24
},
"aggs": {
"sale_sum": {
"sum": {
"field": "saleQty"
}
}
},
"meta":{
"bucket_sort": {
"sort": [
{
"sale_sum":{
"order":"desc"
}
}
]
}
}
}
}
}
hours_sales:按小时统计
sale_sum:同样小时的销售数量
bucket_sort:根据销售数量倒序
输出:
{
"month_sales" : {
"meta" : {
"bucket_sort" : {
"sort" : [
{
"sale_sum" : {
"order" : "desc"
}
}
]
}
},
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "21",
"doc_count" : 1490119,
"sale_sum" : {
"value" : 2219320.0
}
},
{
"key" : "22",
"doc_count" : 1394689,
"sale_sum" : {
"value" : 1984438.0
}
},
{
"key" : "23",
"doc_count" : 1169223,
"sale_sum" : {
"value" : 1621883.0
}
},
{
"key" : "20",
"doc_count" : 1135145,
"sale_sum" : {
"value" : 1684774.0
}
},
{
"key" : "12",
"doc_count" : 1101876,
"sale_sum" : {
"value" : 1970868.0
}
},
{
"key" : "11",
"doc_count" : 1087839,
"sale_sum" : {
"value" : 1718736.0
}
},
{
"key" : "13",
"doc_count" : 1029868,
"sale_sum" : {
"value" : 1555518.0
}
},
{
"key" : "10",
"doc_count" : 1019584,
"sale_sum" : {
"value" : 1964907.0
}
},
{
"key" : "15",
"doc_count" : 951064,
"sale_sum" : {
"value" : 1716640.0
}
},
{
"key" : "09",
"doc_count" : 933940,
"sale_sum" : {
"value" : 1509718.0
}
},
{
"key" : "14",
"doc_count" : 930368,
"sale_sum" : {
"value" : 1386315.0
}
},
{
"key" : "16",
"doc_count" : 925275,
"sale_sum" : {
"value" : 1670132.0
}
},
{
"key" : "19",
"doc_count" : 909453,
"sale_sum" : {
"value" : 1392385.0
}
},
{
"key" : "17",
"doc_count" : 863353,
"sale_sum" : {
"value" : 1311020.0
}
},
{
"key" : "18",
"doc_count" : 795198,
"sale_sum" : {
"value" : 1251265.0
}
},
{
"key" : "08",
"doc_count" : 776007,
"sale_sum" : {
"value" : 1253125.0
}
},
{
"key" : "00",
"doc_count" : 771251,
"sale_sum" : {
"value" : 1019472.0
}
},
{
"key" : "07",
"doc_count" : 568447,
"sale_sum" : {
"value" : 919369.0
}
},
{
"key" : "01",
"doc_count" : 369065,
"sale_sum" : {
"value" : 503474.0
}
},
{
"key" : "06",
"doc_count" : 293302,
"sale_sum" : {
"value" : 467315.0
}
},
{
"key" : "02",
"doc_count" : 207584,
"sale_sum" : {
"value" : 293993.0
}
},
{
"key" : "03",
"doc_count" : 139777,
"sale_sum" : {
"value" : 202227.0
}
},
{
"key" : "05",
"doc_count" : 121415,
"sale_sum" : {
"value" : 188120.0
}
},
{
"key" : "04",
"doc_count" : 111086,
"sale_sum" : {
"value" : 166002.0
}
}
]
}
}
如果已销售100w为高峰,由此推断销售高峰期是 20-23点,其次是8-18点。