Save nested hash in redis via a node.js app

后端 未结 2 1437
暗喜
暗喜 2020-12-13 01:08

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

{
users : 
    \"alex\" : { \"email\" : \"alex@gmail.com\",
           \"password\" : \"alex123         


        
相关标签:
2条回答
  • 2020-12-13 01:12

    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" : "alex@gmail.com",
               "password" : "alex123"},
        "sandra" : { "email" : "sandra@gmail.com",
               "password" : "sandra123"},
        ...
    }
    $x = incr idx:user
    hmset user:$x email alex@gmail.com password alex123
    sadd list:user $x
    
    $x = incr idx:user
    hmset user:$x email sandra@gmail.com password sandra123
    sadd list:user $x
    

    Hope this possible solution helps

    0 讨论(0)
  • 2020-12-13 01:18

    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.

    0 讨论(0)
提交回复
热议问题