Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum value of all Key in Redis

Tags:

string

redis

sum

In Redis DB, i have many key in String type to save dowloads time with a application, example:

   Key            value
20131028:1         100
20131028:2         15
20131028:3         10
..........

I want to sum all value of all key by redis command, please helpe me solve it. Thank you so much.

like image 707
Thanh Tien Avatar asked Oct 29 '13 08:10

Thanh Tien


1 Answers

Redis is not designed to do this kind of things. You will better served by a RDBMS, MongoDB, or something like ElasticSearch.

Still, if you need to do it (to be launched from a shell):

$ redis-cli keys '20131028:*' | awk '{print "get "$1}' | redis-cli | awk '{x+=$1} END { print x }'

An other way to do it is to use a Lua server-side script:

$ redis-cli eval "local keys = redis.call('keys',KEYS[1]) ; local sum=0 ; for _,k in ipairs(keys) do sum = sum + redis.call('get',k) end ; return sum" 1 '20131028:*'

In both cases, performance will suck if you have many keys in the Redis instance, and the instance will be blocked for all connections while the keys are scanned.

like image 198
Didier Spezia Avatar answered Sep 27 '22 16:09

Didier Spezia