Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving and retrieving array of strings in Redis

I'm looking for some examples of getting and setting arrays of strings, and I can't seem to find one or make it work.

The strings themselves are SecureRandom.hex values. Think of them like invite codes. I want to create a pair of key/values:

1) Key=> invite:code:88bb4bdfef Value=> userid

2) Key=> userid:invite:codes Value => 88bb4bdfef,73dbfac453,etc... (one entry for each of the prior set)

I'm just getting stuck on managing the values in the second key/value pair.

UPDATE: So the challenge is that if I create an array and set it like so:

foo=Array.new
foo.push("abc")
foo.push("def")

at this point foo looks like: ["abc","def"]

So I set foo in redis, the retrieve it to bar:

$redis.set(:foo,foo)
bar=$redis.get(:foo)

Now bar looks like: "[\"abc\",\"def\"]"

like image 582
Webjedi Avatar asked May 30 '13 19:05

Webjedi


People also ask

Can we store array in Redis cache?

You could store an array of unique ids, each one the key of a seperately stored hash.

How strings are stored in Redis?

Keys that hold strings can only hold one value; you cannot store more than one string in a single key. However, strings in Redis are binary-safe, meaning a Redis string can hold any kind of data, from alphanumeric characters to JPEG images. The only limit is that strings must be 512 MB long or less.

Can Redis only store strings?

As we have mentioned earlier that Redis is a key-value store, but that doesn't mean that it stores only string keys and string values. Redis supports different types of data structures as values. The key in Redis is a binary-safe String, with a max size of 512 MB, but you should always consider creating shorter keys.

Can Redis store lists?

Redis reads lists from left to right, and you can add new list elements to the head of a list (the “left” end) with the lpush command or the tail (the “right” end) with rpush . You can also use lpush or rpush to create a new list: lpush key value.


1 Answers

You want lists or sets here, rather than simple keys. Here's an example using Redis' set functionality:

$redis.sadd("userid:invite:codes", ["88bb4bdfef", "73dbfac453"])
$redis.smembers("userid:invite:codes")
=> ["88bb4bdfef", "73dbfac453"]
like image 81
Chris Heald Avatar answered Nov 03 '22 01:11

Chris Heald