Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REDIS - Get value of multiple keys

Tags:

redis

How do I get the value of multiple keys from redis using a sorted set?

zadd Users 0 David
zadd Users 5 John
zadd Users 15 Linda
zrevrange Users 0 -1 withscores

This will have two users in it.

How can I retrieve the users with key 'David' and 'Linda' in one query?

like image 974
musdy Avatar asked May 30 '12 10:05

musdy


People also ask

How fetch multiple keys Redis?

In Redis, the GET command is typically used to return the value of a single key that holds a string. But what if we need the values from multiple keys? We can use the MGET command.

Can Redis have multiple keys?

Redis quickly stretched this concept with data types, where a single key could refer to multiple (even millions of) pieces of data. As modules came to the ecosystem, the idea of a key was stretched even further because a single piece of data could now span multiple keys (for a RediSearch index, for example).

How do I get Redis all keys?

Redis GET all Keys To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.


2 Answers

You can use Redis MGET

redis> MGET key1 key2 nonexisting
1) "Hello"
2) "World"
3) (nil)

More here http://redis.io/commands/mget

like image 170
Hemant_Negi Avatar answered Sep 28 '22 11:09

Hemant_Negi


There are multiple ways to do it without introducing a new command in Redis.

For instance, you can fill a temporary set with the names you are interested in, then calculate the intersection between the temporary set and the zset:

multi
  sadd tmp David Linda ... and more ...
  zinterstore res 2 tmp Users weights 0 1
  zrange res 0 -1 withscores
  del tmp res
exec

With pipelining, this will only generate one roundtrip and you can fill an arbitrary number of input parameters in tmp.

With Redis 2.6, you can also wrap these lines into a server-side Lua script to finally get a command accepting an input list and returning the result you want:

eval "redis.call( 'sadd', 'tmp', unpack(KEYS) );
      redis.call( 'zinterstore', 'res', 2, 'tmp', 'Users', 'weights', 0, 1 );
      local res = redis.call( 'zrange', 'res', 0, -1, 'withscores' );
      redis.call( 'del', 'res', 'tmp' ) ; 
      return res
     " 2 David Linda

You can safely assume no new command will be added to Redis if it can easily been implemented using scripting.

like image 34
Didier Spezia Avatar answered Sep 28 '22 13:09

Didier Spezia