REDIS - get the value of several keys

How to 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 

It will have two users.

How can I get users with the keys "David" and "Linda" in one request?

+4
source share
4 answers

There are several ways to do this without introducing a new command in Redis.

For example, you can populate a temporary set with names that interest you, and then calculate the intersection between the temporary set and 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 lead to the generation of only one reverse transition, and you can fill in an arbitrary number of input parameters in tmp.

With Redis 2.6, you can also wrap these lines in a server-side Lua script to finally get a command that accepts an input list and returns the desired result:

 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 

We can safely assume that the new command will not be added to Redis, if it can be easily implemented using scripts.

+5
source

You can use Redis MGET

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

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

+5
source

One uses a sorted set because you want to deal with sorted elements. What you are asking for is not to use the sorted set as a sorted set. If you don't care about the sort order, then perhaps a sorted set is not what you are looking for. You can already get some keys, but not arbitrary.

If your main goal is to get some arbitrary keys, use a hash and hmget. If your primary need is to access a sorted set, use a sorted set and either send the script trace or pipeline to a series of zscore calls.

+1
source

You cannot get this with a single command. The closest thing you can do to get it in one answer:

 MULTI ZSCORE Users David ZSCORE Users Linda EXEC 

EDIT . Alternatively, you can maintain a parallel hash with user ratings and request it using

 HMGET UserScores David Linda 
0
source

Source: https://habr.com/ru/post/1415133/


All Articles