Redis-rb pushing hash into list

12,608

Solution 1

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

Solution 2

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.

Share:
12,608
0xSina
Author by

0xSina

umadbr0

Updated on June 04, 2022

Comments

  • 0xSina
    0xSina almost 2 years

    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