Manjeet Singh
Manjeet Singh

Reputation: 2398

how to use spop command with count if set have that much (count) element in set

Let suppose I want to pop 3 elements from the set, how I ensure that only pop if 3 elements present in a set otherwise return any error or other msg

How to use "spop" command with "count" argument.

Upvotes: 1

Views: 428

Answers (1)

LeoMurillo
LeoMurillo

Reputation: 6774

What you want is to call SCARD myKey to test the number of members, and based on the result call SPOP.

SPOP with COUNT will return up to COUNT members, meaning if your set only has one or two, they'll be SPOPed and returned.

You probably want to do this with one atomic operation. So you have to use Lua Scrips:

EVAL "if redis.call('SCARD', KEYS[1]) >= tonumber(ARGV[1]) then return redis.call('SPOP', KEYS[1], ARGV[1]) else return redis.error_reply(KEYS[1]..' does NOT have at least '..ARGV[1]..' members') end" 1 myKey myNumber

Let's take a look at the script:

if redis.call('SCARD', KEYS[1]) >= tonumber(ARGV[1]) then 
    return redis.call('SPOP', KEYS[1], ARGV[1]) 
else 
    return redis.error_reply(KEYS[1]..' does NOT have at least '..ARGV[1]..' members')
end

KEYS[1] refers to the key parameter, the set you're interested in. It is important to pass keys through parameters for your script to be supported in a Redis Cluster.

ARGV[1] is an additional argument to pass your number of desired members, in your question, it is 3.

The script is run atomically server-side within Redis, and it is compiled only once as Redis caches it internally.

You can use SCRIPT LOAD to load the script and then reuse it with EVALSHA, to also improve networking performance.

Upvotes: 4

Related Questions