public
Last active

Counters with Redis Sorted Sets

  • Download Gist
downloads_counter_sorted_sets.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
# ===============================
# Counters with Redis Sorted Sets
# ===============================
 
redis-cli DEL downloads:total downloads:total:today downloads:files:total downloads:files:2011-05-10
 
# --------------
# STORING COUNTS
# --------------
# On each hit for file, do this:
 
# > Totals
redis-cli INCR downloads:total
redis-cli INCR downloads:total:today
 
# > Individual files
# GET /downloads/file1.mpg
redis-cli ZINCRBY downloads:files:total 1 /downloads/file1.mpg
redis-cli ZINCRBY downloads:files:2011-05-10 1 /downloads/file1.mpg
# GET /downloads/file1.mpg
redis-cli ZINCRBY downloads:files:total 1 /downloads/file1.mpg
redis-cli ZINCRBY downloads:files:2011-05-10 1 /downloads/file1.mpg
# GET /downloads/file2.mpg
redis-cli ZINCRBY downloads:files:total 1 /downloads/file2.mpg
redis-cli ZINCRBY downloads:files:2011-05-10 1 /downloads/file2.mpg
 
# > Set expire at 2011-05-10 23:59:59
redis-cli EXPIREAT downloads:total:today 1305064799
 
# --------------
# GETTING COUNTS
# --------------
 
# First, the obvious.
 
echo '> Total counts, all time'
redis-cli GET downloads:total
 
echo '> Total counts, today'
redis-cli GET downloads:total:today
 
echo '> 10 most downloaded files, all the time'
redis-cli ZREVRANGE downloads:files:total 0 10 WITHSCORES
 
echo '> 10 most downloaded files on 2011-05-10'
redis-cli ZREVRANGE downloads:files:2011-05-10 0 10 WITHSCORES
 
# Second, timelines.
 
echo '> 10 most downloaded files between 2011-05-10 and <OTHER DATE>'
redis-cli ZUNIONSTORE downloads:timeline 2 downloads:files:2011-05-10 downloads:files:2011-05-09 # <OTHER DATE>
redis-cli ZREVRANGE downloads:timeline 0 10 WITHSCORES

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.