Redis:返回存储在数据库中的所有值 [英] Redis: Return all values stored in a database

查看:126
本文介绍了Redis:返回存储在数据库中的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用 Redis 在 DB 0 中存储各种应用程序配置.

We're using Redis to store various application configurations in a DB 0.

是否可以针对数据库中的每个键/值对查询 Redis,而无需执行两个单独的查询并自己加入键/值对?

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('*')

... 其中 kv 将返回元组元组、列表列表或字典:

... Where kv would return a tuple of tuples, list of lists, or a dictionary:

然而,在搜索 StackOverflow、Google 和 Redis 文档后,我能得出的唯一解决方案(我还没有发现其他人问这个问题......)类似于以下内容:

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.

相反,我的问题是:有没有办法说嘿Redis,将数据库中的每个字符串值都返回给我"而不必询问键,然后查询基于的值在返回的键上?

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 中不同类型之间存在差异,因此您必须查看数据类型以确定如何从键中获取值.所以:

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)

这篇关于Redis:返回存储在数据库中的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆