Notes are based of 7DB - Redis - Day 1 & 2
Follow the setup instructions
No collection of data structures would be complete without sets. To illustrate, let's add tags to our sites:
sadd edu cs.montana.edu umt.edu nyu.edu unc.edu
sadd cs cs.montana.edu google.com acm.org
But sets are only really useful if we can perform set operations like intersection
sinter edu cs
Or difference
sdiff edu cs
Or Union
sunion edu cs
Sorted sets are a little slower to work with over hashes (since operations take
time proportional to the log of the size of the set instead of const). Sorted
operations are prefixed with Z
. Let's created a sorted list of visits per
shorted url:
zadd visits 10 um 100 msu 50 goog
We can retrieve by range
zrange 1 2
And change scores with ZINCRBY
zincrby visits 10 msu
One of my favorite uses for Redis is a cache, but as with all good caching
systems, you must have someway to determine if data is no longer valid. Time is
a great option, which can be accomplished with EXPIRY
for example
set ice "I'm melting...."
expire ice 10
And now lets check
> exists ice
(integer) 1
> exists ice
(integer) 0
In fact, we can set and expire as a 1 liner
setex ice 10 "I'm melting...."
exists ice
...
And we can check the TTL
setex ice 10 "I'm melting...."
ttl ice
...
ttl ice
A common operation in a system is incrementing a counter. Often, one is tempted to do the following:
set my-counter 0
get my-counter
... proccessing ...
... update counter
set my-counter 1
Question If there are multiple users, what is the problem?
So, if all you are doing is incrementing, redis has an increment function to make this easier:
incr my-counter
In fact we can control the amount of the increment
incrby my-counter 10
But what if you want to do a bunch of commands together? Transactions would be helpful!
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set dave http://millman.us
QUEUED
127.0.0.1:6379> incr my-counter
QUEUED
127.0.0.1:6379> exec
1) OK
2) (integer) 13
Question What happens if you miss type a command and have an error while in a transaction?
Note that transactions in Redis are different than we have seen in other DBs. Each command is queued and then run as a batch. So if I run
127.0.0.1:6379> multi
127.0.0.1:6379> set a 1
127.0.0.1:6379> set b 2
127.0.0.1:6379> set c 3
127.0.0.1:6379> discard
None of the previous commands will have run
You can use the commands FLUSHDB
and FLUSHALL
to remove all keys from the
current db and all dbs. (Note that we didn't cover here, but you can change to
different DBs with SELECT
).
Write Redis commands (or a sequence of commands) for the following:
-
Creates two sets
A
andB
such thatA \intersect B
is non-empty -
In a transaction, implement symmetric difference. Hint You will need to make some temp sets (look at
SUNIONSTORE
andSINTERSTORE
). You must cleanup any temporary data that you create.