Redis-rb pushing hash into list Redis-rb pushing hash into list ruby ruby

Redis-rb pushing hash into list


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


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.