Angel Todorov
Angel Todorov

Reputation: 1533

Redis hash search by field and value

here is my use case:

I have a simple client/server app, where the communication goes thru socket.io. Since I need to keep track between room name and its corresponding socket owner, I decided to create simple Redis hash, where, each pair is . This hash allows me to quickly find specific room owner socketId by its room name. So far so good. The above hash is updated on subscribe backend event, using very simple haset call via node_redis redis.client.hset(keyRoomToSocketId, room, socketId, cb); This makes sure, each time a new socket arrives and creates its own room with a unique name, to set its socketId to the hash along with it's corresponding field - room.

Now, I would like on socket disconnect event to find this pair and set socketId to empty string. Apparently (tell me if I am wrong), I cannot search the hash by socketId. What I have in my mind is to make one more hash in parallel, in which, the pair to be reversed, i.e. . This will allow me to search second hash by socketId, retrieve room, delete the pair from there and then search first hash and set socketId to "" into the corresponding pair.

Is there anything I am missing and can I make this in a more efficient manner, using Redis?

Upvotes: 0

Views: 715

Answers (2)

Angel Todorov
Angel Todorov

Reputation: 1533

Actually, in the light of the fact, I am using redis along with socket.io, I ended up with just one hash, where pair is . As a second hash, I am using socket object on the backend - when subscribe event fires, I assign room to socket.ownRoom field. The on disconnect event, I am using this field from socket object and search into the only hash.

Upvotes: 0

Itamar Haber
Itamar Haber

Reputation: 49942

This should work - your thinking is correct. What you'll be doing is basically a two-way mapping, and a Hash or two are simple and efficient for that, with the main "price" being the duplication of data. Denormalization is a common practice with NoSQL and specifically Redis.

Upvotes: 1

Related Questions