REDIS - Get value of multiple keys

2020-05-27 03:55发布

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?

标签: redis
4条回答
看我几分像从前
2楼-- · 2020-05-27 04:38

You can use Redis MGET

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

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

查看更多
Anthone
3楼-- · 2020-05-27 04:39

You cannot get this with one command. The closest you can do to get it in one response:

MULTI
ZSCORE Users David
ZSCORE Users Linda
EXEC

EDIT: Alternatively, you can maintain a parallel hash with users' scores, and query it with

HMGET UserScores David Linda
查看更多
beautiful°
4楼-- · 2020-05-27 04:51

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

If your primary goal is to retrieve multiple arbitrary keys, use a hash and hmget. If your primary need is to access a sorted set, use sorted set and either go the scripting route or pipeline a series of zscore calls.

查看更多
聊天终结者
5楼-- · 2020-05-27 04:54

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.

查看更多
登录 后发表回答