Redis ZREMRANGEBYSCORE – How to remove elements of sorted set by score range

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about how to remove elements of the sorted set value having score between a specific range. For this, we will use Redis ZREMRANGEBYSCORE command.

ZREMRANGEBYSCORE Command

This command remove all the elements of the sorted set value, whose score is greater than equal to min ( inclusive ) score and less than equal to max ( inclusive ) score passed as an argument. 

By default min and max arguments are closed interval (inclusive) but it is possible to specify them as an open interval (exclusive) by prefixing them with ( character. For example:- 

ZREMRANGEBYSCORE set (1 5 

Will remove all elements with 1 < score <= 5 while:

ZREMRANGEBYSCORE set (5 (10

Will remove all the elements with 5 < score < 10 (5 and 10 excluded).

min and max argument can be -inf (negative infinity) and +inf (positive infinity) so that you are not required to know the highest or lowest score in the sorted set.

An error is returned, if the key exists but value stored at the key is not of sorted set datatype. 

The syntax of Redis ZREMRANGEBYSCORE command is as follows:- 

Syntax :-

redis host:post> ZREMRANGEBYSCORE <keyname> <min> <max>

Output :-

- (integer) reply, representing number of removed elements.
- 0, if key does not exists.
- Error, if key exist and value stored at the key is not a sorted set.

Example :-

Redis ZREMRANGEBYSCORE

References :-

  1. ZREMRANGEBYSCORE Command Docs

That’s all for how to remove elements of the sorted set value having score between specific range. If you liked it, please share your thoughts in comments section and share it with others too.