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.
I think you're misunderstanding how hashes work. You can't have two identical fields with different values. Your second HMSET command is overwriting the values from the first command. You will either need to use unique fields or a different key.
You can't have multiple items with the same key in a hash. However, if you want to either retrieve all items or a single row by key you can use JSON:
If you don't want to use json you'll have to use multiple hashes, with a hash being a row in the table. You can support the get all function by also storing a set that contains the key of each of the hashes.
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:
AT QUERY TIME:
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).