Redis - 在字典 HMGET 中获取值 [英] Redis - Get values inside a dict HMGET

查看:90
本文介绍了Redis - 在字典 HMGET 中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 redis 中创建了一个密钥,如下所示:-

I've created a key in the redis as following:-

In [1]: import redis

In [2]: conn = redis.Redis('localhost')

In [3]: user = {
   ...:         'name': 'username',
   ...:         'age': 25,
   ...:         'likes': ['football', 'swimming'],
   ...:         'response': {
   ...:                 'a': 1,
   ...:                 'b': 2
   ...:         }
   ...: }

In [4]: conn.hmset("pythonDict", user)
Out[4]: True

In [5]: conn.hgetall("pythonDict")
Out[5]: 
{'age': '25',
 'likes': "['football', 'swimming']",
 'name': 'username',
 'response': "{'a': 1, 'b': 2}"
}

所以,现在我想获取nameage 等的值

So, now I want to get the values of name, age etc.

我做了以下事情:-

In [9]: conn.hmget("pythonDict","age", "likes")
Out[9]: ['25', "['football', 'swimming']"]

按预期工作.

现在我想在响应中获取 a 的值.如何直接获取 response[a] 的值,而不对其进行迭代,即不在应用程序级别???

Now I'm stuck at a point where I want to get the value of a inside response. How can I directly get the value of response[a], without iterating over it, ie not at the application level???

推荐答案

Redis 不支持哈希中的嵌套数据结构.您的客户已将它们(likesresponse)编码为字符串(可能使用 repr(),但也可能使用 JSON)和 hgetall() 将它们作为字符串返回.

Redis does not support nested data structures in hashes. Your client has encoded them (likes and response) as strings (probably using repr(), but perhaps JSON), and hgetall() returns them as strings.

因此,没有 Redis 命令可以让您获得 a 的值.但是,您可以将嵌套数据结构显式编码为 JSON,然后编写一个简单的 Lua 脚本 来提取值在服务器上.您将使用包含的 JSON 库 来解压 response 并返回值a.

So there is no Redis command that is going to get you the value of a. However, you could explicitly encode the nested data structures as JSON and then write a simple Lua script to extract the value on the server. You would use the included JSON library to unpack response and return the value of a.

这篇关于Redis - 在字典 HMGET 中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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