Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to do sum/count/groupby in Redis?

Tags:

redis

For a Redis list (or set/zset/hset)

['5', '5', '5', '5', '4', '3', '3', '3', '2', '2', '2', '2', '1', '1', '1']

What's the best way to stat it, as sql did

select count(key), sum(key) from table group by key; 

Wishing client loop is not the only way.......

like image 790
fanlix Avatar asked Sep 18 '12 09:09

fanlix


1 Answers

The best way is to store the sum as a separate key, and to update whenever you add/remove a value from your set/hash/zset.

In Redis, you should try to model your data according to your access patterns. If you need the sum at runtime, pre-compute and store the sum. If you want sum on a hourly/daily/monthly basis, you will have to create appropriately named keys.

like image 110
Sripathi Krishnan Avatar answered Jan 21 '23 06:01

Sripathi Krishnan