通过node.js应用将嵌套的哈希保存在Redis中 [英] Save nested hash in redis via a node.js app
问题描述
我正在使用node_redis,我想保存一个结构:
I'm using node_redis and I'd like to save a structure like:
{
users :
"alex" : { "email" : "alex@gmail.com",
"password" : "alex123"},
"sandra" : { "email" : "sandra@gmail.com",
"password" : "sandra123"},
...
}
当前,我为每个用户创建一个JSON对象:
Currently, for each user I create a JSON object:
jsonObj = { "email" : "alex@gmail.com",
"password" : "alex123"}
然后做
db.hmset("alex", JSON.stringify(jsonObj))
是否可以将此结构嵌入到另一种结构中(用户使用该结构?) 如何设置具有这种结构的users ["alex"]?
Is it possible to embedded this strucute in another structure (the users one ?) How could I set users["alex"] with this structure ?
推荐答案
据我所知,Redis中不对嵌套结构提供本机支持,但是可以使用set + hash对其进行建模(类似于分层树). 哈希最适合存储单个JSON对象的字段和值.我要做的是为每个用户存储一个前缀(这是Redis 惯例 ),例如:
As far as I know there isn't native support for nested structures in Redis, but they can be modeled for example with set+hash (similar to hierarchical trees). Hashes are probably best suited for storing fields and values of single JSON object. What I would do is to store each user with a prefix (which is a Redis convention), for example:
db.hmset("user:alex", JSON.stringify(jsonObj));
,然后使用集合将用户分组为一个名为users
的密钥.然后,我可以通过 smembers 命令获取所有用户密钥,并分别使用 hgetall .
and then use sets to group users into one set with a key named users
. I can then get all of the users keys by smembers command and access each of them individually with hgetall.
这篇关于通过node.js应用将嵌套的哈希保存在Redis中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!