Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Strings  ›  Lesson

SET and GET

SET 12 minSET stores a string under a key, replacing whatever was there, and GET returns it, or nil when the key does not exist.

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)
  • SET always replies OK and replaces any old value. There is no separate "update".
  • GET replies 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.

SET word:today comet NXStep 1 of 4
  1. Does the key exist?

    Yes: word:today holds "planet".

Drills

Answer fast — trust the rule.

quick drill

word:today holds "planet". What does SET word:today comet reply?

quick drill

word:tomorrow does not exist. What does SET word:tomorrow comet XX reply?

quick drill

word:today holds "planet". What does SET word:today comet GET reply?

quick drill

player:asha is a hash. What does GET player:asha reply?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainSET with conditions

Wordcraft wants to reserve a username only if nobody has it yet. Explain which SET option you would use, what Redis replies when the name is free and when it is taken, and why a plain GET followed by SET is not safe.