Redis Basics
Here are my notes on Redis.
Installation, Start, and Shutdown
I installed WSL and then installed Redis using sudo.
- To start Redis, cd to
/usr/binand runsudo ./redis-server - To connect to Redis, cd to
/usr/binand runsudo ./redis-cli - To shutdown Redis, run
shutdownin the redis-cli, and Redis will save an RDB snapshot before exiting - To check whether Redis is running, run
ps -ef | grep redis - To kill the process, run
kill -9 <pid>
Commands
keys *returns all keys. This command also supports regex patternsdbsizereturns the number of keysexpire keysets the TTL of the key in secondspexpiresets the TTL in millisecondsexpireatsets the absolute time when the key will expire
ttl keyreturns the remaining time of the key-1means it won’t expire-2means it has already expired- Non-negative values show the countdown in seconds
set key valuesetnx key valueonly sets the value when a key does not existmset k1 v1 k2 v2 k3 v3 ...sets multiple key-value pairs- This can save network bandwidth!
get keymget k1 k2 k3gets multiple keys
rename old_key new_keyrenames the old key to the new key- Use
renamenxfor safer operation, so it won’t override existing keys
- Use
Naming Convention
Naming convention for keys is very important.
namespace:entity:id:attribute
Here we use : as the separator.
Types
String
- Size limit: 512MB
incranddecrcan operate on strings!- Only when the string can be parsed into a numeric value. For example,
"9"can be incremented but"9hello"cannot incrby key incrementincreases the value of the key by the incrementincrbyfloat key incrementperforms the same operation for float typesappend key stringappends a string to the existing string
- Only when the string can be parsed into a numeric value. For example,
Hash
The hash here is essentially a hashmap.
The structure is key-field-value.
Syntax: hset name f1 v1 [field value]
Other operations:
hset: set field-value pair for a keyhget: get the value of a key-fieldhdel: delete a fieldhlen: returns the number of fields in the hashmaphkeys: returns all the fields in the hashmaphvals: returns all the values in the hashmaphmget key f1 f2 ...: get multiple fields from the hashmap
Note: String vs Hashmap
For example, to store information like:
[
{ "id": 1, "name": "john", "age": 30 },
{ "id": 2, "name": "jane", "age": 25 }
]
If we use strings to store the data:
set user:1:name john
set user:1:age 30
set user:2:name jane
set user:2:age 25
This creates too many keys and makes it hard to join all the data for a specific user.
A better approach:
hset user:1 name john age 30
hset user:2 name jane age 25
This implementation is much better.
List
List is an ordered array of elements.
It can hold up to 2^32 - 1 elements.
You can insert elements into the head or tail of the linked list.
lpush: adds a new element to the head of the list. It returns the length of the listrpush: adds a new element to the tail of the listpushcommands support pushing multiple elements into a list, for example:rpush mylist 0 1 2 3 4
lpopandrpop: remove and return the element from the head (and tail) of the listblpopis the blocking version oflpopblpop key timeoutis the syntax- When timeout is zero and the list is empty, the Redis engine will wait until the list becomes non-empty, then remove the element
- the
pushcommands do not have blocking behavior
lrange mylist 0 -1: returns all elements in the list.0is the start index and-1is the end index- here,
lsimply means “list”, not “left”
- here,
lset key index element: sets the value of the element at a specific index
With lists, you can implement:
- A queue with
lpushandrpop - A blocking queue with
blpushandbrpop - A stack with
lpushandlpop
Set
Set is an unordered collection of unique elements.
It can hold up to 2^32 - 1 elements.
It supports set operations like intersection and union.
sadd key v1 v2 ...: adds elementssmembers key: returns all elements in a setsrem key v1 v2 ...: removes elementssismember key v1: checks if an element is in the set.0means false while1means truesinter k1 k2 ...: returns the intersectionsinterstore destination key [key ...]: calculates the intersection and stores the result in thedestinationkey
sunion k1 k2 ...: returns the unionsdiff k1 k2 ...: returns the difference of two sets
ZSet
ZSet is ordered collection of unique elements. This data structure is very critical for implementing leaderboard.
TL;DR: to return the top k users in the leaderboard:
ZADD scores 100 user:1
ZADD scores 30 user:2 10 user:3
ZINCRBY scores 10 user:3
ZADD scores 10 user:4 15 user:5 6 user:6
ZINCRBY scores 60 user:6
ZINCRBY scores -72 user:1
ZREVRANGE scores 0 4 WITHSCORES # top 5 users
zadd key score member [score member ...]: for each member, there’s a scorezaddalso comes with options likeNXandXXzcard keyreturns the number of elements in the zsetzscore key memberreturns the score of a memberzrank key memberreturns the ranking. ranking is sorted by score asczrevrankreturns the ranking by score in descending order
zremremove a member from the setzincrby key increment member: increase the score by increment! Useful for real-time game score updateszrange key start stop: returns the members within the range of [start, stop][REV]: for descending order[WITHSCORES]: for showing the score[BYSCORE]: you can do a range query by scores! For example, I want to find all the users whose scores are between [90, 100]