Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a query to add multiple values to a key in REDIS Hashes?

Tags:

redis

I went through the command list on REDIS Hashes.Is it possible to assign multiple values to a hash key in REDIS? For instance,I am trying to represent the following table in form of a hash.

 Prod_Color  |   Prod_Count  |   Prod_Price   |   Prod_Info
------------------------------------------------------------
  Red        |       12      |       300      |   In Stock
  Blue       |        8      |       310      |   In Stock

I tried the following hash commands subsequently

HMSET Records Prod_Color "Red" Prod_Count 12 Prod_Price 300 Prod_Info "In Stock"

HMSET Records Prod_Color "Blue" Prod_Count 8 Prod_Price 310 Prod_Info "In Stock"

However,when I try to retrieve the hash using the command HGETALL Records, I am seeing only the second row of inserted values(i.e. Blue,8,310,In Stock)! I understand that I can create a separate hash and insert the second row of values,however, I intend to insert all the values in a single hash.

like image 252
abhijit k Avatar asked Jul 28 '11 20:07

abhijit k


1 Answers

What you could do, and I saw this in other places besides my code, is to key the hash using a suffix. You probably have a suffix which identifies each record, I will use the colors here:

AT INSERT TIME:

HMSET Records:red Prod_Color "Red" Prod_Count 12 Prod_Price 300 Prod_Info "In Stock"
HMSET Records:blue Prod_Color "Blue" Prod_Count 8 Prod_Price 310 Prod_Info "In Stock"

/* For each HMSET above, you issue SADD */
SADD Records:Ids red
SADD Records:Ids blue

AT QUERY TIME:

/* If you want to get all products, you first get all members */
SMEMBERS Records:Ids

/* ... and then for each member, suppose its suffix is ID_OF_MEMBER */
HGETALL Records:ID_OF_MEMBER

/* ... and then for red and blue (example) */
HGETALL Records:red
HGETALL Records:blue

You probably want to use the primary key as the suffix, since this should be available to you from the relational database records. Also, you must maintain the set of members (e.g. SREM Records:Ids red), when deleting hash keys (e.g. DEL Records:red). And also remember that Redis is really good as an improved cache, you must set it up well to persist values (and maintain performance with that).

like image 52
Niloct Avatar answered Oct 19 '22 01:10

Niloct