Skip to content

Commit 75ad1cb

Browse files
chayimmalinaa96AvitalFineRedis
committed
LT and GT support for ZADD (redis#1509)
Co-authored-by: malinaa96 <[email protected]> Co-authored-by: Avital Fine <[email protected]>
1 parent 1503c72 commit 75ad1cb

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
@@ -2871,7 +2871,8 @@ def xtrim(self, name, maxlen, approximate=True):
28712871
return self.execute_command('XTRIM', name, *pieces)
28722872

28732873
# SORTED SET COMMANDS
2874-
def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False):
2874+
def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False,
2875+
gt=None, lt=None):
28752876
"""
28762877
Set any number of element-name, score pairs to the key ``name``. Pairs
28772878
are specified as a dict of element-names keys to score values.
@@ -2902,6 +2903,9 @@ def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False):
29022903
if incr and len(mapping) != 1:
29032904
raise DataError("ZADD option 'incr' only works when passing a "
29042905
"single element/score pair")
2906+
if nx is True and (gt is not None or lt is not None):
2907+
raise DataError("Only one of 'nx', 'lt', or 'gr' may be defined.")
2908+
29052909
pieces = []
29062910
options = {}
29072911
if nx:
@@ -2913,6 +2917,10 @@ def zadd(self, name, mapping, nx=False, xx=False, ch=False, incr=False):
29132917
if incr:
29142918
pieces.append(b'INCR')
29152919
options['as_score'] = True
2920+
if gt:
2921+
pieces.append(b'GT')
2922+
if lt:
2923+
pieces.append(b'LT')
29162924
for pair in mapping.items():
29172925
pieces.append(pair[1])
29182926
pieces.append(pair[0])

tests/test_commands.py

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

1473+
@skip_if_server_version_lt('6.2.0')
1474+
def test_zadd_gt_lt(self, r):
1475+
1476+
for i in range(1, 20):
1477+
r.zadd('a', {'a%s' % i: i})
1478+
assert r.zadd('a', {'a20': 5}, gt=3) == 1
1479+
1480+
for i in range(1, 20):
1481+
r.zadd('a', {'a%s' % i: i})
1482+
assert r.zadd('a', {'a2': 5}, lt=1) == 0
1483+
1484+
# cannot use both nx and xx options
1485+
with pytest.raises(exceptions.DataError):
1486+
r.zadd('a', {'a15': 155}, nx=True, lt=True)
1487+
r.zadd('a', {'a15': 155}, nx=True, gt=True)
1488+
r.zadd('a', {'a15': 155}, lx=True, gt=True)
1489+
14731490
def test_zcard(self, r):
14741491
r.zadd('a', {'a1': 1, 'a2': 2, 'a3': 3})
14751492
assert r.zcard('a') == 3

0 commit comments

Comments
 (0)