Redis ZREMRANGEBYLEX – How to remove elements of sorted set by value range

5 years ago Lalit Bhagtani 0

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

ZREMRANGEBYLEX Command

This command removes all the elements of the sorted set value, whose values (string representation of element) are between min and max arguments. Here all the elements in a sorted set value are inserted with the same score, in order to force lexicographical ordering.

The min and max arguments must start with ( or [, where [ specifies closed interval (inclusive) and ( specifies open interval (exclusive). For example :- 

ZREMRANGEBYLEX set [a [f

Will remove all elements with a <= element <= f while:

ZREMRANGEBYLEX set [a (f

Will remove all the elements with a <= element < f

The min and max arguments can have special values of + or , where + specifies positive infinite strings and specifies negative infinite strings, so for example the command ZREMRANGEBYLEX set – + will remove all the elements of the sorted set value.

An empty set is returned, if a key does not exist and an error is returned, if a key exists but value stored at the key is not of sorted set datatype. The syntax of Redis ZREMRANGEBYLEX command is as follows:- 

Syntax :-

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

Output :-

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

Example :-

Redis ZREMRANGEBYLEX

References :-

  1. ZREMRANGEBYLEX Command Docs

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