21

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?

Joshua Burns
  • 8,268
  • 4
  • 48
  • 61
  • 1
    Just for strings, or you want to query all data types? `MGET` returns `nil` for anything that's not a string. – raffian Oct 09 '13 at 23:38
  • All values are currently stored as strings, so just strings are fine. – Joshua Burns Oct 10 '13 at 16:14
  • If you need it for debugging purposes, you might want to check out the [following answer](https://stackoverflow.com/a/8079165/52499). – x-yuri Sep 23 '20 at 10:20

1 Answers1

42

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)
ideawu
  • 2,287
  • 1
  • 23
  • 28
  • 12
    Where do the `KV`, `HASH` and `ZSET` come from? I do not see them if I do `dir(redis)`. – Leonid Jun 05 '17 at 22:06
  • @ideawu, it would be worth answering the anove mention comment - Because I'm at a loss as well. – Joshua Burns Jan 08 '20 at 02:43
  • Keep in mind that if it is saved in binary like `b'string'` you will have to check the type against the string in binary. Example: `if type == b'string'` – Matteo Guarnerio Feb 10 '21 at 13:29
  • @MatteoGuarnerio you can decode the values by default. So something like `r = redis.StrictRedis('localhost', 6379, charset="utf-8", decode_responses=True)`. Credit: https://stackoverflow.com/a/44032018/3480297 – Adam Jul 05 '22 at 11:37