How to store array of hashes in redis

半城伤御伤魂 提交于 2019-12-04 00:48:51

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!