I have an index transactions with fields user_id, amount and category. I would like to calculate the average amount per user and category, and then finish off with just getting the total average amount per category. The SQL would look like this:
SELET AVG(average), category from
(SELECT user_id, category, AVG(amount) AS average FROM transactions WHERE amount < 100000
GROUP BY user_id, category) AS a1
GROUP BY category
I'm only getting so far as to having a response of a bucket with all user ids, and then inside that, a bucket with the average amounts per category (for the user). I don't understand how to add yet another aggregation to do what I'm after.
{
"aggs": {
"group_by_users": {
"terms": {
"field": "user_id.keyword"
},
"aggs": {
"group_by_category": {
"terms": {
"field": "category.keyword"
},
"aggs": {
"average_amount": {
"avg": {
"field": "amount"
}
}
}
}
}
}
}
}
Any help is very much appreciated.
Edit: Example requested so here is first some sample data and then the intermediate result which will end with the wanted result at the bottom.
-----------------------------------------
| user_id | category | amount |
-----------------------------------------
| 1 | insurances | 1000 |
| 1 | transport | 50 |
| 1 | transport | 100 |
| 2 | insurances | 700 |
| 2 | insurances | 200 |
| 2 | transport | 300 |
-----------------------------------------
Calculation for user 1 transport: (50+100)/2
So, the first thing that needs to happen is a group by user_id and category to get the average per user and category.
That would yield:
-----------------------------------------
| user_id | category | average |
-----------------------------------------
| 1 | insurances | 1000 |
| 1 | transport | 75 |
| 2 | insurances | 450 |
| 2 | transport | 300 |
-----------------------------------------
It's important to understand I can't do an average for all users together, I need the average spend per user, per category, first.
So now I just want to group by category and calculate the average amount:
-----------------------------
| category | average |
-----------------------------
| insurances | 725 |
| transport | 187,5 |
-----------------------------
Example for insurances: (1000 + 450) / 2