Daniël Zwijnenburg
Daniël Zwijnenburg

Reputation: 2560

Getting multiple key values from Redis

I'm currently playing around with Redis and i've got a few questions. Is it possible to get values from an array of keys?

Example:

users:1:name "daniel"
users:1:age  "24"

users:2:name "user2"
users:2:age  "24"

events:1:attendees "users:1", "users:2"

When i redis.get events:1:attendees it returns "users:1", "users:2". I can loop through this list and get users:1, get users:2. But this feels wrong, is there a way to get all the attendees info on 1 get?!

In rails i would do something like this:

@event.attendees.each do |att|
  att.name
end

But in redis i can't because it returns the keys and not the actual object stored at that key.

thanks :)

Upvotes: 22

Views: 30168

Answers (2)

Didier Spezia
Didier Spezia

Reputation: 73306

Doing a loop on the items and synchronously accessing each element is not very efficient. With Redis 2.4, there are various ways to do what you want:

  • by using the sort command
  • by using pipelining
  • by using variadic parameter commands

With Redis 2.6, you can also use Lua scripting, but this is not really required here.

By the way, the data structure you described could be improved by using hashes. Instead of storing user data in separate keys, you could group them in a hash object.

Using the sort command

You can use the Redis sort command to retrieve the data in one roundtrip.

redis> set users:1:name "daniel"
OK
redis> set users:1:age 24
OK
redis> set users:2:name "user2"
OK
redis> set users:2:age 24
OK
redis> sadd events:1:attendees users:1 users:2
(integer) 2
redis> sort events:1:attendees by nosort get *:name get *:age
1) "user2"
2) "24"
3) "daniel"
4) "24"

Using pipelining

The Ruby client support pipelining (i.e. the capability to send several queries to Redis and wait for several replies).

keys = $redis.smembers("events:1:attendees")
res = $redis.pipelined do
   keys.each do |x|
      $redis.mget(x+":name",x+":age")
   end
end

The above code will retrieve the data in two roundtrips only.

Using variadic parameter command

The MGET command can be used to retrieve several data in one shot:

redis> smembers events:1:attendees
1) "users:2"
2) "users:1"
redis> mget users:1:name users:1:age users:2:name users:2:age
1) "daniel"
2) "24"
3) "user2"
4) "24"

The cost here is also two roundtrips. This works if you can guarantee that the number of keys to retrieve is limited. If not, pipelining is a much better solution.

Upvotes: 38

Ofer Zelig
Ofer Zelig

Reputation: 17508

You can use Redis' EVAL command to send it a Lua script that runs a loop "server side" and return the results in a block.

Upvotes: 5

Related Questions