We're using Redis to store various application configurations in a DB 0.
Is it possible to query Redis for every key/valuie pair within the database, without having to perform two separate queries and joining the key/value pairs yourself?
I would expect functionality similar to the following:
kv = redis_conn.getall()
# --OR-- #
kv = redis_conn.mget('*')
... Where kv
would return a tuple of tuples, list of lists, or a dictionary:
However after scouring StackOverflow, Google and Redis documentation, the only solution I can derive (I haven't yet found anyone else asking this question..) is something similar to the following:
import redis
red = redis.Redis(host='localhost', db=0)
keys = red.keys()
vals = red.mget(keys)
kv = zip(keys, vals)
Am I crazy here, in assuming there to be a more elegant approach to this problem?
Every value within this database is a String.
My question is not how to retrieve values for each unique data type or data-type related at all.
Rather, my question is: Is there a way to say "hey Redis, return to me every string value in the database"
without having to ask for the keys, then query for the values based on the keys returned?
Redis GET all Keys To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.
The Redis KEYS command returns all the keys in the database that match a pattern (or all the keys in the key space). Similar commands for fetching all the fields stored in a hash is HGETALL and for all fetching the members of a SMEMBERS. The keys in Redis themselves are stored in a dictionary (aka a hash table).
A Redis server has 16 databases by default. You can check the actual number by running redis-cli config get databases. In interactive mode, the database number is displayed in the prompt within square braces. For example, 127.0. 0.1:6379[13] shows that the 13th database is in use.
When MGET is used, Redis returns an array of values.
There are differences between different types in Redis, so you have to look at the data type to determine how to get the values from the key. So:
keys = redis.keys('*')
for key in keys:
type = redis.type(key)
if type == "string":
val = redis.get(key)
if type == "hash":
vals = redis.hgetall(key)
if type == "zset":
vals = redis.zrange(key, 0, -1)
if type == "list":
vals = redis.lrange(key, 0, -1)
if type == "set":
vals = redis. smembers(key)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With