0

I need to store some values. First is post data like: {postid,text,room_name} where postid will be incremented automaticly. and after collecting some posts I need to put them into username so I will have:

 Thomas
    1,text,room_name
    2,text,room_name
    3,text,room_name
 Kris
    1,text,room_name
    2,text,room_name
    3,text,room_name

I think I should use hashes but I don't know how to push them into those user names. What i do is:

 db.incr('id',function(id){
 db.hmset(id,'room',room,'text',text,redis.print)
 })
Kriss
  • 435
  • 1
  • 10
  • 22

1 Answers1

0

There are always multiple ways how to organize data in redis database and you must decide which one to use based on how do you want to retrieve your data.

So, if you want to read all posts for given name, than you can keep separate hash for each name. The key name could be something like

user:posts:<username>

The prefix "name:posts:" is to make sure that there will be no collision with other keys in your database. Hash key would be post id, and value could be json

{"text": "<post text>", "room_name": "<name of room>"}

I have marked parts which are supposed to be replaced with real values with <>).

It seems from your example that posts for each person have its own index, so we need separate key to hold index for each person, lets name it "user:postId:<username>".

This is the code to store data in such structure:

var redis = require('redis'), db = redis.createClient(),
    username = 'Thomas', post = 'Hello World!', room = 'stackoverflow';

db.incr('user:postId:' + username, function (error, id) {
    if (error) throw error;
    db.hset(
        'user:posts:' + username, id,
        JSON.stringify({post: post, room: room}),
        redis.print
    );
});

To read the data from redis:

db.hgetall('user:posts:' + username, function (error, replies) {
    console.log(replies);
});

This will print:

{ '1': '{"post":"Hello World!","room":"stackoverflow"}' }

This assumes that you don't need to access the fields post and room separately - but for this kind of query, it is easier, because you get your result using single hgetall.

m6k
  • 678
  • 5
  • 14