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

前端 未结 3 628
伪装坚强ぢ
伪装坚强ぢ 2020-12-31 16:49

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

相关标签:
3条回答
  • 2020-12-31 17:23

    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).

    0 讨论(0)
  • 2020-12-31 17:31

    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.

    0 讨论(0)
  • 2020-12-31 17:36

    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:

    Records red = {color:red, price:12, info:"300 in stock"}
    Records blue = {color:blue, price:8, info:"310 in stock"}
    

    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.

    0 讨论(0)
提交回复
热议问题