Using redis-rb and mapped_mget()

69 views
Skip to first unread message

Mason Jones

unread,
Jan 28, 2010, 5:53:52 PM1/28/10
to redi...@googlegroups.com
I have a quick question about using the redis-rb client and its
mapped_mget() method... I've looked through the source to see how it
might be used, and I've found what seems like some unexpected
behavior. It may be that there's a different way to do this, but if
not I can look at potentially patching it if it seems like an
improvement.

After getting a bunch of keys from set 'objects' (just for example purposes):

redis.sort('objects', { :limit => [ offset, per_page ])

I then want to turn around and use mget to grab the details of the
items. I also want the keys for each one, and it seems that
mapped_mget() is for this purpose? So I tried:

p = r.mapped_mget(r.sort('objects', { :limit => [0, 5]}))

Unfortunately, it looks as though mapped_mget() will only take a list
of keys, not an array? What I get back is:

p.keys
=> [["object:5459789:data", "object:5893120:data",
"object:7232572:data", "object:7312762:data", "object:5235635:data"],
nil]

The array itself is returned as the first key, followed by nil. But if
I do this:

p = r.mapped_mget("object:5459789:data", "object:5893120:data")
p.keys
=> ["object:5459789:data", "object:5893120:data"]

That works as expected, with each key mapped to its value.

Does it seem reasonable to expect that mapped_mget() could take an
array, and then the results of a set() call can be passed directly in,
as I showed above?

Thanks!

Alex Kahn

unread,
Mar 25, 2010, 11:07:43 AM3/25/10
to Redis DB
Hi Mason,

You're right: mapped_mget takes a series of key arguments, rather than
an array. But you can convert from an array to a list of arguments
with Ruby's * (splat) operator. So if you have key1 => value1 and key2
=> value2 in Redis, and you have the Ruby array: keys = ['key1',
'key2'], you need to do:

r.mapped_mget(*keys)

Ruby will "expand" the array into a list of arguments. That should get
you the result you desire.

It might be smart for redis-rb to raise an error if mapped_mget
receives an array argument, since it will not behave as expected in
this case. Maybe this is something Ezra, the redis-rb author, would
accept a patch for.

Cheers,
Alex

Reply all
Reply to author
Forward
0 new messages