0
0
Redisquery~5 mins

SPOP for random removal in Redis

Choose your learning style9 modes available
Introduction

SPOP lets you remove and get a random item from a set in Redis. It helps when you want to pick something randomly and remove it at the same time.

When you want to pick a random winner from a list of participants and remove them from the pool.
When you need to randomly assign tasks from a set and ensure no task is assigned twice.
When you want to randomly remove an item from a collection to balance load or usage.
When you want to simulate drawing random cards from a deck stored as a set.
Syntax
Redis
SPOP key [count]

key is the name of the set.

count is optional. If given, it removes and returns that many random elements.

Examples
Removes and returns one random element from the set named myset.
Redis
SPOP myset
Removes and returns 3 random elements from myset. If the set has fewer than 3 elements, it returns all.
Redis
SPOP myset 3
Sample Program

This adds 4 fruits to the set, removes 2 random fruits, then shows the remaining fruits.

Redis
SADD fruits apple banana cherry date
SPOP fruits 2
SMEMBERS fruits
OutputSuccess
Important Notes

If you use SPOP without count, it removes and returns one random element.

If count is larger than the set size, it returns all elements and empties the set.

Removed elements are no longer in the set after SPOP.

Summary

SPOP removes and returns random elements from a Redis set.

You can remove one or multiple elements by specifying count.

It is useful for random selection and removal in one step.