Joshua Burns
Joshua Burns

Reputation: 8572

Redis: Return all values stored in a database

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?

Additional Info

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?

Upvotes: 21

Views: 42948

Answers (1)

ideawu
ideawu

Reputation: 2337

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)

Upvotes: 43

Related Questions