我正在尝试用Elasticsearch计算一些百分比,但我有一个(小)问题。我希望ES计算以下内容:“(wins / Total)* 100”。
所以我补充道:
"bucket_script": {
"buckets_paths": {
"total": "TotalStatus",
"wins": "TotalWins"
},
"script": " (total/ wins) * 100"
}
我的ES请求,如下所示:
{
"size": 0,
"query": {
"bool": {
"must": [
{
"query_string": {
"query": "*",
"analyze_wildcard": true
}
}
],
"must_not": []
}
},
"aggs": {
"status": {
"terms": {
"field": "status.raw"
}
},
"wins": {
"terms": {
"field": "status.raw",
"include": {
"pattern": "Accepted|Released|Closed"
}
}
},
"losses": {
"terms": {
"field": "status.raw",
"include": {
"pattern": "Rejected"
}
}
},
"TotalStatus": {
"sum_bucket": {
"buckets_path": "status._count"
}
},
"TotalWins": {
"sum_bucket": {
"buckets_path": "wins._count"
}
},
"TotalLosses": {
"sum_bucket": {
"buckets_path": "losses._count"
}
}
}
}
然而,这会返回以下错误:
{
"error": {
"root_cause": [
{
"type": "parsing_exception",
"reason": "Could not find aggregator type [buckets_paths] in [bucket_script]",
"line": 54,
"col": 28
}
],
"type": "parsing_exception",
"reason": "Could not find aggregator type [buckets_paths] in [bucket_script]",
"line": 54,
"col": 28
},
"status": 400
}
有什么想法吗?
答案 0 :(得分:0)
我用bucket_script
玩过很多次但是我想它可能不可能,因为它不能是顶级聚合,而且你需要来自同一父聚合的total_wins和total_status都有一个数值而我认为这可能是不可能的。
但可以通过scripted metric aggregation
解决{
"size": 0,
"aggs": {
"win_loss_ratio": {
"scripted_metric": {
"init_script": "_agg['win_count'] = 0; _agg['total_count'] = 0; _agg['win_status']=['Accepted','Released','Closed'];",
"map_script": "if (doc['status.raw'].value in _agg['win_status']) { _agg['win_count']+=1};if (doc['status.raw'].value) { _agg['total_count']+=1}",
"combine_script": "return [_agg['win_count'],_agg['total_count']];",
"reduce_script": "total_win = 0; total_status_count=0; for (a in _aggs) { total_win += a[0]; total_status_count += a[1] }; if(total_win == 0) {return 0} else {return (total_status_count/total_win) * 100}"
}
}
}
}