Reputation: 581
I started using redis (with ruby on rails) recently and I want to know what is the best way to store this kind of data.
data1 = {
'name2' : {
'age' : xxx,
'height' : xxx,
},
'name2' : {
'age' : xxx,
'weight' : xxx,
}
}
data2 = {
'class1' : {
'num' : xxx,
'location' : xxx,
'teacher' : xxx,
},
'class2' : {
'num' : xxx,
'location' : xxx,
'teacher' : xxx,
}
}
I have tried using the hash map (hset, hmset, hget, hmget) commands but they dont seem to work with the sub keys like "age" and "height".
Upvotes: 2
Views: 2070
Reputation: 3784
In Redis hashes you can't store nested elements directly that's why you get those errors.
If you want to be able to access directly items like data1.name1 or data2.class2 then using hashes is the right thing. And to store them you can put everything inside data1.name1 as a json:
HSET data1 name1 {'num' : xxx,'location' : xxx,'teacher' : xxx,}
and to load the data it would be:
HGET data1 name1
But if you don't want to load these fields directly and you can load all what is inside data1 or data2 then vaughanj answer is what you need.
Upvotes: 3
Reputation: 143
It appears that you are trying to store some JSON in Redis. Using the redis-rb gem it's pretty trivial to do this. For example you could do the following:
redis = Redis.new
redis.set("key", data1)
Then when you would like to retrieve this data, I would do something like this:
data = JSON.parse(redis.get("key"))
This will retrieve the JSON object that you have stored in Redis with the key named "key", and then parse that into a Ruby hash. I hope this helps!
Upvotes: 6