Scripted metrics aggregation based on complicated terms buckets as an entry data

See this similar "devices with last status of X" question here: Find servers whose last logged event was "error"