Hello.
I was handling game log, and I was trying to check every user's gold at the end of each day with aggs and scripted metrics. My english is bad, so I'll jump right to the code
GET /game/log/_search
{
"query": {
"match_all" : {}
},"size": 0,
"aggs": {
"human": {
"terms": {
"field": "playerid",
"size": 10000000
},
"aggs": {
"histo_bro": {
"date_histogram": {
"field": "@timestamp",
"interval": "day"
},
"aggs": {
"lastgold": {
"scripted_metric": {
"init_script": "_agg['time'] = 0",
"map_script": "if(doc['@timestamp'].value > _agg['time']) {_agg['time'] = doc['@timestamp'].value ; _agg['gold'] = doc['gold'].value}",
"combine_script": "return _agg"
// ,"reduce_script": "res=0; for(t in _aggs){if(t==null) return 100};return res"
// ,"reduce_script": "chktime = 0 ; res = 0; for(t in aggs){if(t.time > chktime){chktime = t.time ; res = t.gold}}; return res"
,"reduce_script": "return _aggs"
}
}
}
}
}
}
the script above will show me something like this whole lot of time:
{
"key": //userid,
"doc_count": 107,
"histo_bro": {
"buckets": [
{
"key_as_string": "2016-07-12T00:00:00.000Z",
"key": 1468281600000,
"doc_count": 107,
"lastgold": {
"value": [
{
"time": 1468287233096,
"gold": 105414
},
{
"time": 1468287554348,
"gold": 281015
},
{
"time": 1468286842445,
"gold": 165175
},
{
"time": 1468287473573,
"gold": 87537
},
{
"time": 1468287039060,
"gold": 75946
},
{
"time": 1468287234215,
"gold": 106953
},
{
"time": 1468287027673,
"gold": 68126
},
{
"time": 1468287473573,
"gold": 87537
},
{
"time": 1468287553047,
"gold": 277214
},
{
"time": 1468287470048,
"gold": 80241
}
]
}
}
]
}
},
enabling first line of reduce_script (and disabling third) will return :
aggregations": {
"human": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": //userid,
"doc_count": 134,
"histo_bro": {
"buckets": [
{
"key_as_string": "2016-07-12T00:00:00.000Z",
"key": 1468281600000,
"doc_count": 134,
"lastgold": {
"value": 0
}
}
]
}
},
which means t is not null.
but enabling second line of reduce script will throw me exception :
"caused_by": {
"type": "null_pointer_exception",
"reason": "Cannot get property 'time' on null object"
}
Why does this happen? How can I read 'time' and 'gold' from say like _aggs[0] ?