Saving a HASH to Redis on a rails app

2019-03-17 06:52发布

Im just starting off with Redis with Rails so this maybe a dumb question.

I am trying to save a hash to redis server but when I retrieve it its just a string IE.

hash = {"field" => "value", "field2" => "value2"}
$redis.set('data', hash)

#So collecting the data
@data = $redis.get('data')

This is obviously wrong as its returning as a string.

I have also tried looping some results and using the hset ie.

@data.each do |d|
  $redis.hset('data', d.field, d.value)
end

# errror
# ERR Operation against a key holding the wrong kind of value

Not sure where to go. I have deleted the key $redis.del('data') to make sure that was not the issue.

Hope you can advise, Lee

4条回答
Explosion°爆炸
2楼-- · 2019-03-17 07:34

The redis gem will remap your hash like this:

$redis.mapped_hmset "test", { foo: "bar" }
$redis.hgetall "test" => {"foo"=>"bar"}
查看更多
成全新的幸福
3楼-- · 2019-03-17 07:47

When you use $redis.set('data', hash) you actually saving a regular Redis string, even though you use an hash variable (it might be serialized to Json string, but I'm really not sure about it).

Try using $redis.hset('data', hash) (not by looping through the fields as you did).

Another point: Are you sure you've deleted the previous key entirely? Did you try to hset a completely different key to eliminate the option the previous string key is still "out there"?

查看更多
Evening l夕情丶
4楼-- · 2019-03-17 07:50

I should have read the redis docs more thorough.

Answer:

IN
$redis.set 'data', hash.to_json

OUT
data = JSON.parse($redis.get("data"))
查看更多
你好瞎i
5楼-- · 2019-03-17 07:55

In order to save a hash in redis. You must pass the key as a first parameter and then the next parameters must be the keys and values on hmset method.

$redis.hmset('user:007', :name, 'Antonio', :busy, 'maybe', :ping, 'pong')

Happy Coding.

查看更多
登录 后发表回答