SET and GET
Wordcraft shows a "word of the day" on every screen. It changes once a day and is read millions of times. That is the simplest thing Redis can store: one key holding one string value.
The rule
SET replaces, GET reads; a missing key reads as nil.
A Redis string is the most basic value: a sequence of bytes up to 512 MB. It can hold text, a number, JSON or even an image; Redis does not care what the bytes mean.
127.0.0.1:6379> SET word:today orbit
OK
127.0.0.1:6379> GET word:today
"orbit"
127.0.0.1:6379> SET word:today planet
OK
127.0.0.1:6379> GET word:today
"planet"
127.0.0.1:6379> GET word:tomorrow
(nil)SETalways repliesOKand replaces any old value. There is no separate "update".GETreplies with the value in quotes, or(nil)when the key does not exist.- Values with spaces need quotes:
SET motto "play every day".
SET takes useful options after the value:
| Option | Meaning | Reply when it does not apply |
|---|---|---|
EX 60 |
expire after 60 seconds | — |
NX |
only set if the key does not exist | (nil) |
XX |
only set if the key already exists | (nil) |
GET |
return the old value while setting the new one | — |
Key names are free-form, but the common convention is words joined by colons, from general to specific: word:today, player:asha, cache:profile:asha.
One more rule: GET only works on strings. Asking GET for a key that holds a hash or list replies (error) WRONGTYPE Operation against a key holding the wrong kind of value.
The shortcut
Before predicting a SET reply, check two things: Does the key exist now? Does an option make that matter? No NX or XX means the answer is always OK.
Does the key exist?
Yes:
word:todayholds"planet".
Drills
Answer fast — trust the rule.
word:today holds "planet". What does SET word:today comet reply?
word:tomorrow does not exist. What does SET word:tomorrow comet XX reply?
word:today holds "planet". What does SET word:today comet GET reply?
player:asha is a hash. What does GET player:asha reply?
Which command stores a token that deletes itself after 30 minutes?
Remember
- SET replaces, GET reads; a missing key reads as nil.
- Does the key exist? Does NX or XX care? Otherwise SET says OK.
- GET on a non-string key is a WRONGTYPE error, not nil.
