Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis-rb pushing hash into list

Tags:

ruby

redis

Using redis-rb, how can I push a hash into a list? Do I have to JSON encode it or is this natively supported? If so, how can I do it? I only see hset method with a key and key/value pairs.

Thanks

like image 561
0xSina Avatar asked Jan 12 '12 09:01

0xSina


2 Answers

Storing any object (not just hash) as a JSON encoded string is one way to do it.

If your use case allows it you can also store hash IDs within the list and use SORT GET to retrieve additional values.

Example:

r.hmset('person:1', 'name','adam','age','33')
r.hmset('person:2', 'name','eva','age','28')    

r.lpush('occupants', 'person:1')
r.lpush('occupants', 'person:2')

r.sort('occupants', :get => ['*->name'])

To get list names from hashes which IDs are stored within occupants list. You can retrieve multiple fields, but you will get only array back.

For more information check SORT command

like image 192
Radim Avatar answered Nov 02 '22 01:11

Radim


A Redis list is analogous to a Ruby Array. It has no keys.

As discussed in the redis-rb documentation, if you want to store a Ruby object in a Redis value you'll need to serialize it first using e.g. JSON:

Storing objects

Redis only stores strings as values. If you want to store an object inside a key, you can use a serialization/deseralization mechanism like JSON:

>> redis.set "foo", [1, 2, 3].to_json
=> OK

>> JSON.parse(redis.get("foo"))
=> [1, 2, 3]

Your other option would be to store it as a Redis hash, as you mentioned, using e.g. HMSET, but if your only goal is to store and retrieve the object (rather than perform Redis operations on it), that's superfluous.

like image 25
Jordan Running Avatar answered Nov 02 '22 00:11

Jordan Running