database/redis distributedsystem systemdesign

SET Command

The SET command is used to store a string value under a given key. If the key already exists, its value will be overwritten.

SET key value
SET mykey "Hello"
# Output
"OK"

Additional Options:

  • SET key value EX seconds → Set a key with an expiration time (in seconds)
  • SET key value PX milliseconds → Set a key with an expiration time (in milliseconds)
  • SET key value NX → Set a key only if it does not already exist
  • SET key value XX → Set a key only if it already exists

Example with Expiration:

SET mykey "Hello" EX 10

HSET Command

The HSET command is used to store a field-value pair in a hash. Hashes in Redis are similar to JSON objects or dictionaries.

HSET hash_name field value
HSET user:1001 name "Alice" age 30
# Output
(integer) 2

Retrieving Hash Values

  • To get a specific field value:
HGET user:1001 name

Output:

"Alice"
  • To get all fields and values:
HGETALL user:1001

Output:

1) "name"
2) "Alice"
3) "age"
4) "30"

EXPIRE Command

The EXPIRE command sets a time-to-live (TTL) on a key, after which it is automatically deleted.

EXPIRE key seconds
EXPIRE mykey 10

Output:

(integer) 1

To remove expiration (make the key persistent):

PERSIST mykey

TTL Command

The TTL command returns the remaining time (in seconds) before a key expires. If the key has no expiration, it returns -1.

when the TTL (Time-To-Live) expires, the key is **automatically deleted** from Redis.

TTL key
TTL mykey

Output:

(integer) 10

This means the key will expire in 10 seconds.

  • If the key does not exist, TTL returns -2.
  • If the key exists but has no expiration, TTL returns -1.