Quick Redis

Posted on September 2, 2022
Tags: codeetc

Redis uses port 6379

docker start -p 4000:6379 redis:latest 
redis-cli -h 127.0.0.1 -p 4000

1 Basics


redis-server /path/redis.conf        # start redis with the related configuration file
redis-cli                            # opens a redis prompt
sudo systemctl restart redis.service # Restart Redis
sudo systemctl status redis          # Check Redis status

Redis is a hashtable {key::TypeX -> value::TypeY}

2 Basic data types, Polymorphism - datatypes can change

Basic data type for VALUE

3 SET a key-value pair

set user:1000:followers "heh"
# OK

Notice the way we named our key using colons? This allows us to give psuedo complex structure to a simple key-value data struct.
In a meta level we can associate user:1000:followers => [role]:[id]:[property]

3.1 Check if NOT exist before SET

  • Just add NX to the end
set user:1000:followers "heh" NX
# OK
set user:1000:followers "heh" NX
# (nil)

3.2 Check if EXIST before SET

  • Just add XX to the end
set user:1000:followers "heh" XX
# (nil)
set user:1000:followers "heh" 
# OK
set user:1000:followers "Updatedheh" XX
# "Updatedheh"

4 Get all Keys w/ KEYS SCAN

4.1 Example

find all keys with customer id that starts with 1

keys customer:1*
# 1) "customer:1340"
# 2) "customer:1423"
scan 0 MATCH customer:1*
# 1) "94"     <--------- this is LAST SEARCHED INDEX
# 2) (empty list or set)  <---- No matching result in index 0 to 90, DO IT AGAIN
scan 94 MATCH customer:1*
# 1) "154" 
# 2) (empty list or set) <--- AGAIN
scan 154 MATCH customer:1*
# 1) "300"
# 2) 1) "customer:1340"
#    2) "customer:1423"

What happens when if there are no matches?

scan 0 MATCH customer:1bleh COUNT 1000
# 1) "0"   <-----TELLS US NO MORE KEYS TO ITERATE OVER 
# 2) (empty list or set)

6 Caching

7 List

lpop events