If I have below data in ES and dynamoDB. How can I count total books_borrowed using query?
user
user_id: 1, name: "ABC", books_borrwoed: 5, unit_price: 10
user_id: 2, name: "dead", books_borrwoed: 5, unit_price: 10
I cant use loop, as there can be more than 10k records in a month.
CodePudding user response:
You can use sum aggregation, to get the sum of books_borrwed
field
{
"size": 0,
"aggs": {
"total_books": {
"sum": {
"field": "books_borrwoed"
}
}
}
}
Search result will be :
"aggregations": {
"total_books": {
"value": 10.0
}
}
Update 1:
If you need to multiply price of each book by 5, you can use script with sum aggregation
{
"size": 0,
"aggs": {
"total_books": {
"sum": {
"script": {
"lang": "painless",
"inline": "doc['books_borrwoed'].value * 5"
}
}
}
}
}
Search Result will be
"aggregations": {
"total_books": {
"value": 50.0
}
}
And if you want to take the value from your data, you can use below query
{
"size": 0,
"aggs": {
"total_books": {
"sum": {
"script": {
"lang": "painless",
"inline": "doc['books_borrwoed'].value * doc['unit_price'].value"
}
}
}
}
}