2

I am using node_redis client for NodeJS. I have structured data that I am currently trying to store in Redis. Whenever I try to add more key values to the same set, it gets overridden. I'm being chasing it for days and I found that I have to add unique members and then I can add data according to them. I did that part by defining unique keys at the user level but I want to create hash keys with company and username combination. So that, when it goes live; it always generates a unique hash for each user.

JSON:

{
  "Company": "ABC",
  "Users": [
    {
      "Username": "john@gmail.com",
      "Authenticated": false
    },
    {
      "Username": "chris@gmail.com",
      "Authenticated": true
    },
    {
      "Username": "shaun@hotmail.com",
      "Authenticated": true
    }
  ]
}

What I tried so far:

var message = JSON.parse(jsonMessage);

message.Users.forEach(function(user,i){

    redisClient.sadd("users", "user:" + i);

    redisClient.hmset("user:" + i, "Username", user.Username, "Authenticated", user.Authenticated);

});

How I put my data according to the company. Where I should put my company and then add its users respectively as I have data that consists of multiple companies.

What should be the exact binding of the company with its users in Redis?

Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73

1 Answers1

2

It all depends on how you want to access the data but for example you could try to do it like this:

To match your current structure, you may use something like this:

set "company:ABC:users:0:username" "john@gmail.com"
set "company:ABC:users:0:authenticated" 0
set "company:ABC:users:1:username" "chris@gmail.com"
set "company:ABC:users:1:authenticated" 1

With more minimal approach:

set "ABC:john@gmail.com" 0
set "ABC:chris@gmail.com" 1

With potentially more data to store later:

hset "ABC:john@gmail.com" "authenticated" 0
hset "ABC:chris@gmail.com" "authenticated" 1

All of those approaches mean that there are different ways to access the data of course it shows that you can structure your data in many ways. Go to this website where you can try all of those commands online:

What you have to keep in mind is that you cannot have deeply nested structures in Redis. You can have hashes but they are single-level and the multiple levels of nesting is usually emulated using complex keys like "a:b:c" or "a.b.c" - you have to keep that in mind when your original data comes as JSON which can be arbitrarily nested by nature.

rsp
  • 107,747
  • 29
  • 201
  • 177