Python Redis:返回存储在数据库中的所有值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19282580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redis: Return all values stored in a database
提问by Joshua Burns
We're using Redis to store various application configurations in a DB 0.
我们使用 Redis 在 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?
是否可以为数据库中的每个键/值对查询 Redis,而不必执行两个单独的查询并自己加入键/值对?
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:
... 哪里kv
会返回元组元组、列表列表或字典:
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:
然而,在搜索 StackOverflow、Google 和 Redis 文档后,我能得出的唯一解决方案(我还没有发现其他人问这个问题......)类似于以下内容:
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?
相反,我的问题是:有没有办法说"hey Redis, return to me every string value in the database"
而不必询问键,然后根据返回的键查询值?
采纳答案by ideawu
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:
Redis 中不同类型之间存在差异,因此您必须查看数据类型以确定如何从键中获取值。所以:
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)