1、比较同一条数据两个字段之间的差异
eg:比较两个时间字段相差的天数
POST my_date_index/_search
{
"size": 0,
"aggs": {
"my_dates_diff": {
"avg": {
"script": """
long d1 = doc['created_at'].value.toInstant().toEpochMilli();
long d2 = doc['check_in'].value.toInstant().toEpochMilli();
long differenceInMillis = d1-d2;
return Math.abs(differenceInMillis/86400000);
"""
}
}
}
2、查询聚合后字段占总数的百分比
POST /sales/_search
{
"size": 0,
"aggs" : {
"sales_per_month" : {
"date_histogram" : {
"field" : "date",
"interval" : "month"
},
"aggs": {
"total_sales": {
"sum": {
"field": "price"
}
},
"t-shirts": {
"filter": {
"term": {
"type": "t-shirt"
}
}
},
"t-shirt-percentage": {
"bucket_script": {
"buckets_path": {
"tShirtSales": "t-shirts>_count",
"totalSales": "total_sales"
},
"script": "params.tShirtSales / params.totalSales * 100"
}
}
}
}
}
}
其实也可以自己将数据拿出来计算



