Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save nested hash in redis via a node.js app

Tags:

node.js

redis

I'm using node_redis and I'd like to save a structure like:

{
users : 
    "alex" : { "email" : "[email protected]",
           "password" : "alex123"},
    "sandra" : { "email" : "[email protected]",
           "password" : "sandra123"},
    ...
}

Currently, for each user I create a JSON object:

jsonObj = { "email" : "[email protected]",
            "password" : "alex123"}

and do a

db.hmset("alex", JSON.stringify(jsonObj))

Is it possible to embedded this strucute in another structure (the users one ?) How could I set users["alex"] with this structure ?

like image 216
Luc Avatar asked Apr 18 '11 10:04

Luc


2 Answers

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));

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.

like image 157
yojimbo87 Avatar answered Oct 15 '22 06:10

yojimbo87


You could store the sub structure as an object and store it's id within the main structure, rather like a pointer. So, given your example, I would do the following

{
users : 
    "alex" : { "email" : "[email protected]",
           "password" : "alex123"},
    "sandra" : { "email" : "[email protected]",
           "password" : "sandra123"},
    ...
}
$x = incr idx:user
hmset user:$x email [email protected] password alex123
sadd list:user $x

$x = incr idx:user
hmset user:$x email [email protected] password sandra123
sadd list:user $x

Hope this possible solution helps

like image 16
Lloyd Moore Avatar answered Oct 15 '22 06:10

Lloyd Moore