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.