Skip to content

Commit c7ecb1d

Browse files
chayimmalinaa96AvitalFineRedis
authored
LT and GT support for ZADD (#1509)
Co-authored-by: malinaa96 <[email protected]> Co-authored-by: Avital Fine <[email protected]>
1 parent e706445 commit c7ecb1d

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

redis/client.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2866,7 +2866,8 @@ def xtrim(self, name, maxlen, approximate=True):
28662866
return self.execute_command('XTRIM', name, *pieces)
28672867

28682868
# SORTED SET COMMANDS
2869-
def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False):
2869+
def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False,
2870+
gt=None, lt=None):
28702871
"""
28712872
Set any number of element-name, score pairs to the key ``name``. Pairs
28722873
are specified as a dict of element-names keys to score values.
@@ -2897,6 +2898,9 @@ def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False):
28972898
if incr and len(mapping) != 1:
28982899
raise DataError("ZADD option 'incr' only works when passing a "
28992900
"single element/score pair")
2901+
if nx is True and (gt is not None or lt is not None):
2902+
raise DataError("Only one of 'nx', 'lt', or 'gr' may be defined.")
2903+
29002904
pieces = []
29012905
options = {}
29022906
if nx:
@@ -2908,6 +2912,10 @@ def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False):
29082912
if incr:
29092913
pieces.append(b'INCR')
29102914
options['as_score'] = True
2915+
if gt:
2916+
pieces.append(b'GT')
2917+
if lt:
2918+
pieces.append(b'LT')
29112919
for pair in mapping.items():
29122920
pieces.append(pair[1])
29132921
pieces.append(pair[0])

tests/test_commands.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1462,6 +1462,23 @@ def test_zadd_incr_with_xx(self, r):
14621462
# redis-py
14631463
assert r.zadd('a', {'a1': 1}, xx=True, incr=True) is None
14641464

1465+
@skip_if_server_version_lt('6.2.0')
1466+
def test_zadd_gt_lt(self, r):
1467+
1468+
for i in range(1, 20):
1469+
r.zadd('a', {'a%s' % i: i})
1470+
assert r.zadd('a', {'a20': 5}, gt=3) == 1
1471+
1472+
for i in range(1, 20):
1473+
r.zadd('a', {'a%s' % i: i})
1474+
assert r.zadd('a', {'a2': 5}, lt=1) == 0
1475+
1476+
# cannot use both nx and xx options
1477+
with pytest.raises(exceptions.DataError):
1478+
r.zadd('a', {'a15': 155}, nx=True, lt=True)
1479+
r.zadd('a', {'a15': 155}, nx=True, gt=True)
1480+
r.zadd('a', {'a15': 155}, lx=True, gt=True)
1481+
14651482
def test_zcard(self, r):
14661483
r.zadd('a', {'a1': 1, 'a2': 2, 'a3': 3})
14671484
assert r.zcard('a') == 3

0 commit comments

Comments
 (0)