PureDevOps Community

Redis Get All Keys and Its Values

I am aware that in order to get all the keys in Redis, I have to use KEYS *, but is there a way to output all keys along with their values?

Solution : 1

You can use MGET to get the values of multiple keys in a single go.

Example:

redis> SET key1 "Hello"
"OK"
redis> SET key2 "World"
"OK"
redis> MGET key1 key2 nonexisting
1) "Hello"
2) "World"
3) (nil)

For listing out all keys & values you’ll probably have to use bash or something similar, but MGET can help in listing all the values when you know which keys to look for beforehand.

Solution: 2

One can put the below script in a file and execute to get the desired result ,

#!/bin/bash

# Default to '*' key pattern, meaning all redis keys in the namespace
REDIS_KEY_PATTERN="${REDIS_KEY_PATTERN:-*}"
for key in $(redis-cli --scan --pattern "$REDIS_KEY_PATTERN")
do
    type=$(redis-cli type $key)
    if [ $type = "list" ]
    then
        printf "$key => \n$(redis-cli lrange $key 0 -1 | sed 's/^/  /')\n"
    elif [ $type = "hash" ]
    then
        printf "$key => \n$(redis-cli hgetall $key | sed 's/^/  /')\n"
    elif [ $type = "smembers" ]
    then
        printf "$key => $(redis-cli smembers $key)\n"
    elif [ $type = "zset" ]
    then
        printf "$key => $(redis-cli zrange $key 0 -1)\n"
    elif [ $type = "set" ]
    then
        printf "$key => $(redis-cli smembers $key)\n"
    else
        printf "$key => $(redis-cli get $key)\n"

    fi
done

Output:

deviceq:job:types => 3CAE67E8-F151-41DB-8A02-B6AD90518FDE
deviceq:jobs:inactive => 01|2
leader:6953dfcfadadd4b0ad021994cffca16852d09473 => 8c42c478-595c-40d2-bb9f-d41466835228
deviceq:jobs:3CAE67E8-F151-41DB-8A02-B6AD90518FDE:inactive => 01|2
deviceq:3CAE67E8-F151-41DB-8A02-B6AD90518FDE:jobs =>
  1
  1