简体   繁体   中英

How to model this hash with values as list in redis?

I have to store data in redis, where the data to be stored is of form

{
  "KEY" : {
        "k1":["v1", "v2", "v3"],
        "k2":["v4", "v5"],
        "k3":["v1", "v2]}
    },
  "KEY1" :{
        "k1":["v11", "v2"],
        "k2":["v4", "v15", "v3"],
        "k3":["v12", "v2]}
    }
}

According the documentation, we can not have list as a value in the hash data structure. What is the best way for modelling this, the list is generated one value at a time, so I need to append or add. Should there be different database for each of the top level keys?, or should there be different instances of redis which needs to be brought up so that the top level keys is used to identify the specific database or instance in which the mid level key can be used as a key to load the values in a list or set?

Redis is quite flexible regarding how you can structure your data, but here is a possible approach.

Since hash values have to be strings, they can be keys referring to lists. So you can create a list of values under a top-level key:

redis> lpush list_value:k1 v1
(integer) 1
redis> lpush list_value:k1 v2
(integer) 2
redis> lpush list_value:k1 v3
(integer) 3

Then you set the key referring to that list as a value of a hash:

redis> hset KEY k1 list_value:k1
(integer) 1

To fetch your list of values, you first get the key where those values are stored:

redis> hget KEY k1
"list_value:k1"

Then you use that key to retrieve the list of values:

redis> lrange list_value:k1 0 -1
1) "v3"
2) "v2"
3) "v1"

You should use namespaces (typically based on colon separators) to name the keys pointing to your lists of values in order to avoid clashes with the keys of your hashes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM