4. Why Redis?
● Fast
● Easy to learn
● Various data types
● Solve a specific set of problems
○ Good: Caching, Statistical data, Recoverable state,
Worker Queue
○ Bad: 100% consistent dataset required, Data is
larger than memory
7. Key
● Redis key is Binary safe, this means that you can use
any binary sequence as a key:
○ string
○ content of a JPEG file
○ also, empty string
8. Rules about Keys
● Too long keys are not a good idea
○ memory-wise, costly key-comparisons
● Too short keys are often not a good idea
○ more readable
○ id:10:pass => id:10:password
● Try to stick with a schema
○ “object-type:id:field” => “comment:1234:reply.to”
9. Value types
● String
● List of strings
● Sets of strings
● Sorted sets of strings
● Hashes where keys and values are strings
10. String
● The simplest Redis type
● A value can’t be bigger than 512 MB
● SET
● GET
● INCR/INCRBY, DECR/DECRBY
● GETSET
11. 127.0.0.1:6379> set mykey 100
OK
127.0.0.1:6379> get mykey
"100"
127.0.0.1:6379> incr mykey
(integer) 101
127.0.0.1:6379> incrby mykey 5
(integer) 106
127.0.0.1:6379> decr mykey
(integer) 105
127.0.0.1:6379> decrby mykey 2
(integer) 103
127.0.0.1:6379> getset mykey 1
"103"
127.0.0.1:6379> get mykey
"1"
Example Of String
12. List
● Implemented via Linked Lists
● LPUSH
○ add a new element into a list at the head
● RPUSH
○ add a new element into a list at the tail
● LRANGE
13. 127.0.0.1:6379> incr next.news.id
(integer) 1
127.0.0.1:6379> set news:1:title "Redis is simple"
OK
127.0.0.1:6379> set news:1:url "http://code.google.com/redis"
OK
127.0.0.1:6379> lpush submitted.news 1
(integer) 1
Push IDs instead of the actual data
reddit.com example:
14. Sets
● Unordered collections of unique strings
● SADD
● SMEMBERS
● SISMEMBER
● SINTER
○ the intersection between different sets
15. Sorted Sets
● Collections of unique strings with associated
score
● ZADD
○ O(log(N))
● ZRANGE/ZREVRANGE
● ZRANGEBYSCORE
16. ZADD
Add a few selected hackers with their year of birth as score
127.0.0.1:6379> zadd hackers 1940 "Alan Kay"
(integer) 1
127.0.0.1:6379> zadd hackers 1953 "Richard Stallman"
(integer) 1
127.0.0.1:6379> zadd hackers 1965 "Yukihiro Matsumoto"
(integer) 1
127.0.0.1:6379> zadd hackers 1916 "Claude Shannon"
(integer) 1
127.0.0.1:6379> zadd hackers 1969 "Linus Torvalds"
(integer) 1
127.0.0.1:6379> zadd hackers 1912 "Alan Turing"
(integer) 1
18. Sorted Set by different ordering
● Use SORT command
○ Server will waste CPU
● Make another sorted set
○ An alternative for having multiple orders is to add
every element in multiple sorted sets at the same
time.