How to store array of hashes in redis

14,836

Solution 1

The only way AFAIK is to de-reference them. Say you have an array of 2 hashes like: {foo: 'bar', baz: 'qux'}.

You'd store them separately, and then create a SET that references them all:

HMSET myarr:0 foo bar baz qux
SADD myarr myarr:0
HMSET myarr:1 foo bar baz qux
SADD myarr myarr:1

Then you can retrieve them all by querying the set: SMEMBERS myarr and then call HGETALL <key> on all the returned keys to rebuild your original array of hashes.

I hope this makes sense. And if you find a smarter way I'd be happy to hear it.

Solution 2

If you are using a language which supports to/from json conversion, you can convert your hash to json and append it in a list. You can do the following in Ruby:

require 'rubygems'
require 'redis'
require 'json'
require 'pp'

redis = Redis.new(:host => '127.0.0.1', :port => 6379)

h1 = { :k1 => 'v1', :k2 => 'v2' }
redis.rpush('arr', h1.to_json)

h2 = { :k3 => 'v3', :k4 => 'v4' }
redis.rpush('arr', h2.to_json)

hashes = redis.lrange('arr', 0, -1)
hashes.map! { |x| JSON.parse(x) }
pp hashes
Share:
14,836

Related videos on Youtube

XMen
Author by

XMen

Updated on March 27, 2020

Comments

  • XMen
    XMen about 4 years

    I want to store array of hashes in redis , what is best way to code it ?

  • radtek
    radtek about 6 years
    That's the way to do it!
  • RandallB
    RandallB almost 6 years
    This has atomicity problems... if someone updates a field in the hash, etc.
  • MoxGeek
    MoxGeek about 5 years
    that make the logic more complex if you need to remove or edit a hash ...
  • EvgenyKolyakov
    EvgenyKolyakov about 2 years
    This is also super slow 😓
  • EvgenyKolyakov
    EvgenyKolyakov about 2 years
    Can you please explain the complexity? O(?)