forked from valkey-io/valkey-glide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
3694 lines (3039 loc) · 151 KB
/
core.py
File metadata and controls
3694 lines (3039 loc) · 151 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright GLIDE-for-Redis Project Contributors - SPDX Identifier: Apache-2.0
from abc import ABC, abstractmethod
from collections.abc import Mapping
from datetime import datetime, timedelta
from enum import Enum
from typing import (
Dict,
List,
Optional,
Protocol,
Set,
Tuple,
Type,
Union,
cast,
get_args,
)
from glide.async_commands.sorted_set import (
AggregationType,
InfBound,
LexBoundary,
RangeByIndex,
RangeByLex,
RangeByScore,
ScoreBoundary,
ScoreFilter,
_create_z_cmd_store_args,
_create_zrange_args,
)
from glide.constants import TOK, TResult
from glide.protobuf.redis_request_pb2 import RequestType
from glide.routes import Route
from ..glide import Script
class ConditionalChange(Enum):
"""
A condition to the `SET`, `ZADD` and `GEOADD` commands.
- ONLY_IF_EXISTS - Only update key / elements that already exist. Equivalent to `XX` in the Redis API
- ONLY_IF_DOES_NOT_EXIST - Only set key / add elements that does not already exist. Equivalent to `NX` in the Redis API
"""
ONLY_IF_EXISTS = "XX"
ONLY_IF_DOES_NOT_EXIST = "NX"
class ExpiryType(Enum):
"""SET option: The type of the expiry.
- SEC - Set the specified expire time, in seconds. Equivalent to `EX` in the Redis API.
- MILLSEC - Set the specified expire time, in milliseconds. Equivalent to `PX` in the Redis API.
- UNIX_SEC - Set the specified Unix time at which the key will expire, in seconds. Equivalent to `EXAT` in the Redis API.
- UNIX_MILLSEC - Set the specified Unix time at which the key will expire, in milliseconds. Equivalent to `PXAT` in the
Redis API.
- KEEP_TTL - Retain the time to live associated with the key. Equivalent to `KEEPTTL` in the Redis API.
"""
SEC = 0, Union[int, timedelta] # Equivalent to `EX` in the Redis API
MILLSEC = 1, Union[int, timedelta] # Equivalent to `PX` in the Redis API
UNIX_SEC = 2, Union[int, datetime] # Equivalent to `EXAT` in the Redis API
UNIX_MILLSEC = 3, Union[int, datetime] # Equivalent to `PXAT` in the Redis API
KEEP_TTL = 4, Type[None] # Equivalent to `KEEPTTL` in the Redis API
class InfoSection(Enum):
"""
INFO option: a specific section of information:
-SERVER: General information about the Redis server
-CLIENTS: Client connections section
-MEMORY: Memory consumption related information
-PERSISTENCE: RDB and AOF related information
-STATS: General statistics
-REPLICATION: Master/replica replication information
-CPU: CPU consumption statistics
-COMMANDSTATS: Redis command statistics
-LATENCYSTATS: Redis command latency percentile distribution statistics
-SENTINEL: Redis Sentinel section (only applicable to Sentinel instances)
-CLUSTER: Redis Cluster section
-MODULES: Modules section
-KEYSPACE: Database related statistics
-ERRORSTATS: Redis error statistics
-ALL: Return all sections (excluding module generated ones)
-DEFAULT: Return only the default set of sections
-EVERYTHING: Includes all and modules
When no parameter is provided, the default option is assumed.
"""
SERVER = "server"
CLIENTS = "clients"
MEMORY = "memory"
PERSISTENCE = "persistence"
STATS = "stats"
REPLICATION = "replication"
CPU = "cpu"
COMMAND_STATS = "commandstats"
LATENCY_STATS = "latencystats"
SENTINEL = "sentinel"
CLUSTER = "cluster"
MODULES = "modules"
KEYSPACE = "keyspace"
ERROR_STATS = "errorstats"
ALL = "all"
DEFAULT = "default"
EVERYTHING = "everything"
class ExpireOptions(Enum):
"""
EXPIRE option: options for setting key expiry.
- HasNoExpiry: Set expiry only when the key has no expiry (Equivalent to "NX" in Redis).
- HasExistingExpiry: Set expiry only when the key has an existing expiry (Equivalent to "XX" in Redis).
- NewExpiryGreaterThanCurrent: Set expiry only when the new expiry is greater than the current one (Equivalent
to "GT" in Redis).
- NewExpiryLessThanCurrent: Set expiry only when the new expiry is less than the current one (Equivalent to "LT" in Redis).
"""
HasNoExpiry = "NX"
HasExistingExpiry = "XX"
NewExpiryGreaterThanCurrent = "GT"
NewExpiryLessThanCurrent = "LT"
class UpdateOptions(Enum):
"""
Options for updating elements of a sorted set key.
- LESS_THAN: Only update existing elements if the new score is less than the current score.
- GREATER_THAN: Only update existing elements if the new score is greater than the current score.
"""
LESS_THAN = "LT"
GREATER_THAN = "GT"
class GeospatialData:
def __init__(self, longitude: float, latitude: float):
"""
Represents a geographic position defined by longitude and latitude.
The exact limits, as specified by EPSG:900913 / EPSG:3785 / OSGEO:41001 are the following:
- Valid longitudes are from -180 to 180 degrees.
- Valid latitudes are from -85.05112878 to 85.05112878 degrees.
Args:
longitude (float): The longitude coordinate.
latitude (float): The latitude coordinate.
"""
self.longitude = longitude
self.latitude = latitude
class StreamTrimOptions(ABC):
"""
Abstract base class for stream trim options.
"""
@abstractmethod
def __init__(
self,
exact: bool,
threshold: Union[str, int],
method: str,
limit: Optional[int] = None,
):
"""
Initialize stream trim options.
Args:
exact (bool): If `true`, the stream will be trimmed exactly.
Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.
threshold (Union[str, int]): Threshold for trimming.
method (str): Method for trimming (e.g., MINID, MAXLEN).
limit (Optional[int]): Max number of entries to be trimmed. Defaults to None.
Note: If `exact` is set to `True`, `limit` cannot be specified.
"""
if exact and limit:
raise ValueError(
"If `exact` is set to `True`, `limit` cannot be specified."
)
self.exact = exact
self.threshold = threshold
self.method = method
self.limit = limit
def to_args(self) -> List[str]:
"""
Convert options to arguments for Redis command.
Returns:
List[str]: List of arguments for Redis command.
"""
option_args = [
self.method,
"=" if self.exact else "~",
str(self.threshold),
]
if self.limit is not None:
option_args.extend(["LIMIT", str(self.limit)])
return option_args
class TrimByMinId(StreamTrimOptions):
"""
Stream trim option to trim by minimum ID.
"""
def __init__(self, exact: bool, threshold: str, limit: Optional[int] = None):
"""
Initialize trim option by minimum ID.
Args:
exact (bool): If `true`, the stream will be trimmed exactly.
Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.
threshold (str): Threshold for trimming by minimum ID.
limit (Optional[int]): Max number of entries to be trimmed. Defaults to None.
Note: If `exact` is set to `True`, `limit` cannot be specified.
"""
super().__init__(exact, threshold, "MINID", limit)
class TrimByMaxLen(StreamTrimOptions):
"""
Stream trim option to trim by maximum length.
"""
def __init__(self, exact: bool, threshold: int, limit: Optional[int] = None):
"""
Initialize trim option by maximum length.
Args:
exact (bool): If `true`, the stream will be trimmed exactly.
Otherwise the stream will be trimmed in a near-exact manner, which is more efficient.
threshold (int): Threshold for trimming by maximum length.
limit (Optional[int]): Max number of entries to be trimmed. Defaults to None.
Note: If `exact` is set to `True`, `limit` cannot be specified.
"""
super().__init__(exact, threshold, "MAXLEN", limit)
class StreamAddOptions:
"""
Options for adding entries to a stream.
"""
def __init__(
self,
id: Optional[str] = None,
make_stream: bool = True,
trim: Optional[StreamTrimOptions] = None,
):
"""
Initialize stream add options.
Args:
id (Optional[str]): ID for the new entry. If set, the new entry will be added with this ID. If not specified, '*' is used.
make_stream (bool, optional): If set to False, a new stream won't be created if no stream matches the given key.
trim (Optional[StreamTrimOptions]): If set, the add operation will also trim the older entries in the stream. See `StreamTrimOptions`.
"""
self.id = id
self.make_stream = make_stream
self.trim = trim
def to_args(self) -> List[str]:
"""
Convert options to arguments for Redis command.
Returns:
List[str]: List of arguments for Redis command.
"""
option_args = []
if not self.make_stream:
option_args.append("NOMKSTREAM")
if self.trim:
option_args.extend(self.trim.to_args())
option_args.append(self.id if self.id else "*")
return option_args
class GeoUnit(Enum):
"""
Enumeration representing distance units options for the `GEODIST` command.
"""
METERS = "m"
"""
Represents distance in meters.
"""
KILOMETERS = "km"
"""
Represents distance in kilometers.
"""
MILES = "mi"
"""
Represents distance in miles.
"""
FEET = "ft"
"""
Represents distance in feet.
"""
class ExpirySet:
"""SET option: Represents the expiry type and value to be executed with "SET" command."""
def __init__(
self,
expiry_type: ExpiryType,
value: Optional[Union[int, datetime, timedelta]],
) -> None:
"""
Args:
- expiry_type (ExpiryType): The expiry type.
- value (Optional[Union[int, datetime, timedelta]]): The value of the expiration type. The type of expiration
determines the type of expiration value:
- SEC: Union[int, timedelta]
- MILLSEC: Union[int, timedelta]
- UNIX_SEC: Union[int, datetime]
- UNIX_MILLSEC: Union[int, datetime]
- KEEP_TTL: Type[None]
"""
self.set_expiry_type_and_value(expiry_type, value)
def set_expiry_type_and_value(
self, expiry_type: ExpiryType, value: Optional[Union[int, datetime, timedelta]]
):
if not isinstance(value, get_args(expiry_type.value[1])):
raise ValueError(
f"The value of {expiry_type} should be of type {expiry_type.value[1]}"
)
self.expiry_type = expiry_type
if self.expiry_type == ExpiryType.SEC:
self.cmd_arg = "EX"
if isinstance(value, timedelta):
value = int(value.total_seconds())
elif self.expiry_type == ExpiryType.MILLSEC:
self.cmd_arg = "PX"
if isinstance(value, timedelta):
value = int(value.total_seconds() * 1000)
elif self.expiry_type == ExpiryType.UNIX_SEC:
self.cmd_arg = "EXAT"
if isinstance(value, datetime):
value = int(value.timestamp())
elif self.expiry_type == ExpiryType.UNIX_MILLSEC:
self.cmd_arg = "PXAT"
if isinstance(value, datetime):
value = int(value.timestamp() * 1000)
elif self.expiry_type == ExpiryType.KEEP_TTL:
self.cmd_arg = "KEEPTTL"
self.value = str(value) if value else None
def get_cmd_args(self) -> List[str]:
return [self.cmd_arg] if self.value is None else [self.cmd_arg, self.value]
class InsertPosition(Enum):
BEFORE = "BEFORE"
AFTER = "AFTER"
class CoreCommands(Protocol):
async def _execute_command(
self,
request_type: RequestType.ValueType,
args: List[str],
route: Optional[Route] = ...,
) -> TResult: ...
async def _execute_transaction(
self,
commands: List[Tuple[RequestType.ValueType, List[str]]],
route: Optional[Route] = None,
) -> List[TResult]: ...
async def _execute_script(
self,
hash: str,
keys: Optional[List[str]] = None,
args: Optional[List[str]] = None,
route: Optional[Route] = None,
) -> TResult: ...
async def set(
self,
key: str,
value: str,
conditional_set: Optional[ConditionalChange] = None,
expiry: Optional[ExpirySet] = None,
return_old_value: bool = False,
) -> Optional[str]:
"""
Set the given key with the given value. Return value is dependent on the passed options.
See https://redis.io/commands/set/ for more details.
Args:
key (str): the key to store.
value (str): the value to store with the given key.
conditional_set (Optional[ConditionalChange], optional): set the key only if the given condition is met.
Equivalent to [`XX` | `NX`] in the Redis API. Defaults to None.
expiry (Optional[ExpirySet], optional): set expiriation to the given key.
Equivalent to [`EX` | `PX` | `EXAT` | `PXAT` | `KEEPTTL`] in the Redis API. Defaults to None.
return_old_value (bool, optional): Return the old string stored at key, or None if key did not exist.
An error is returned and SET aborted if the value stored at key is not a string.
Equivalent to `GET` in the Redis API. Defaults to False.
Returns:
Optional[str]:
If the value is successfully set, return OK.
If value isn't set because of only_if_exists or only_if_does_not_exist conditions, return None.
If return_old_value is set, return the old value as a string.
Example:
>>> await client.set("key", "value")
'OK'
>>> await client.set("key", "new_value",conditional_set=ConditionalChange.ONLY_IF_EXISTS, expiry=Expiry(ExpiryType.SEC, 5))
'OK' # Set "new_value" to "key" only if "key" already exists, and set the key expiration to 5 seconds.
>>> await client.set("key", "value", conditional_set=ConditionalChange.ONLY_IF_DOES_NOT_EXIST,return_old_value=True)
'new_value' # Returns the old value of "key".
>>> await client.get("key")
'new_value' # Value wasn't modified back to being "value" because of "NX" flag.
"""
args = [key, value]
if conditional_set:
args.append(conditional_set.value)
if return_old_value:
args.append("GET")
if expiry is not None:
args.extend(expiry.get_cmd_args())
return cast(Optional[str], await self._execute_command(RequestType.Set, args))
async def get(self, key: str) -> Optional[str]:
"""
Get the value associated with the given key, or null if no such value exists.
See https://redis.io/commands/get/ for details.
Args:
key (str): The key to retrieve from the database.
Returns:
Optional[str]: If the key exists, returns the value of the key as a string. Otherwise, return None.
Example:
>>> await client.get("key")
'value'
"""
return cast(Optional[str], await self._execute_command(RequestType.Get, [key]))
async def append(self, key: str, value: str) -> int:
"""
Appends a value to a key.
If `key` does not exist it is created and set as an empty string, so `APPEND` will be similar to `SET` in this special case.
See https://redis.io/commands/append for more details.
Args:
key (str): The key to which the value will be appended.
value (str): The value to append.
Returns:
int: The length of the string after appending the value.
Examples:
>>> await client.append("key", "Hello")
5 # Indicates that "Hello" has been appended to the value of "key", which was initially empty, resulting in a new value of "Hello" with a length of 5 - similar to the set operation.
>>> await client.append("key", " world")
11 # Indicates that " world" has been appended to the value of "key", resulting in a new value of "Hello world" with a length of 11.
>>> await client.get("key")
"Hello world" # Returns the value stored in "key", which is now "Hello world".
"""
return cast(int, await self._execute_command(RequestType.Append, [key, value]))
async def strlen(self, key: str) -> int:
"""
Get the length of the string value stored at `key`.
See https://redis.io/commands/strlen/ for more details.
Args:
key (str): The key to return its length.
Returns:
int: The length of the string value stored at `key`.
If `key` does not exist, it is treated as an empty string and 0 is returned.
Examples:
>>> await client.set("key", "GLIDE")
>>> await client.strlen("key")
5 # Indicates that the length of the string value stored at `key` is 5.
"""
return cast(int, await self._execute_command(RequestType.Strlen, [key]))
async def rename(self, key: str, new_key: str) -> TOK:
"""
Renames `key` to `new_key`.
If `newkey` already exists it is overwritten.
See https://redis.io/commands/rename/ for more details.
Note:
When in cluster mode, both `key` and `newkey` must map to the same hash slot.
Args:
key (str) : The key to rename.
new_key (str) : The new name of the key.
Returns:
OK: If the `key` was successfully renamed, return "OK". If `key` does not exist, an error is thrown.
"""
return cast(
TOK, await self._execute_command(RequestType.Rename, [key, new_key])
)
async def renamenx(self, key: str, new_key: str) -> bool:
"""
Renames `key` to `new_key` if `new_key` does not yet exist.
See https://valkey.io/commands/renamenx for more details.
Note:
When in cluster mode, both `key` and `new_key` must map to the same hash slot.
Args:
key (str): The key to rename.
new_key (str): The new key name.
Returns:
bool: True if `key` was renamed to `new_key`, or False if `new_key` already exists.
Examples:
>>> await client.renamenx("old_key", "new_key")
True # "old_key" was renamed to "new_key"
"""
return cast(
bool,
await self._execute_command(RequestType.RenameNX, [key, new_key]),
)
async def delete(self, keys: List[str]) -> int:
"""
Delete one or more keys from the database. A key is ignored if it does not exist.
See https://redis.io/commands/del/ for details.
Note:
When in cluster mode, the command may route to multiple nodes when `keys` map to different hash slots.
Args:
keys (List[str]): A list of keys to be deleted from the database.
Returns:
int: The number of keys that were deleted.
Examples:
>>> await client.set("key", "value")
>>> await client.delete(["key"])
1 # Indicates that the key was successfully deleted.
>>> await client.delete(["key"])
0 # No keys we're deleted since "key" doesn't exist.
"""
return cast(int, await self._execute_command(RequestType.Del, keys))
async def incr(self, key: str) -> int:
"""
Increments the number stored at `key` by one. If the key does not exist, it is set to 0 before performing the
operation.
See https://redis.io/commands/incr/ for more details.
Args:
key (str): The key to increment its value.
Returns:
int: The value of `key` after the increment.
Examples:
>>> await client.set("key", "10")
>>> await client.incr("key")
11
"""
return cast(int, await self._execute_command(RequestType.Incr, [key]))
async def incrby(self, key: str, amount: int) -> int:
"""
Increments the number stored at `key` by `amount`. If the key does not exist, it is set to 0 before performing
the operation. See https://redis.io/commands/incrby/ for more details.
Args:
key (str): The key to increment its value.
amount (int) : The amount to increment.
Returns:
int: The value of key after the increment.
Example:
>>> await client.set("key", "10")
>>> await client.incrby("key" , 5)
15
"""
return cast(
int, await self._execute_command(RequestType.IncrBy, [key, str(amount)])
)
async def incrbyfloat(self, key: str, amount: float) -> float:
"""
Increment the string representing a floating point number stored at `key` by `amount`.
By using a negative increment value, the value stored at the `key` is decremented.
If the key does not exist, it is set to 0 before performing the operation.
See https://redis.io/commands/incrbyfloat/ for more details.
Args:
key (str): The key to increment its value.
amount (float) : The amount to increment.
Returns:
float: The value of key after the increment.
Examples:
>>> await client.set("key", "10")
>>> await client.incrbyfloat("key" , 5.5)
15.55
"""
return cast(
float,
await self._execute_command(RequestType.IncrByFloat, [key, str(amount)]),
)
async def setrange(self, key: str, offset: int, value: str) -> int:
"""
Overwrites part of the string stored at `key`, starting at the specified
`offset`, for the entire length of `value`.
If the `offset` is larger than the current length of the string at `key`,
the string is padded with zero bytes to make `offset` fit. Creates the `key`
if it doesn't exist.
See https://valkey.io/commands/setrange for more details.
Args:
key (str): The key of the string to update.
offset (int): The position in the string where `value` should be written.
value (str): The string written with `offset`.
Returns:
int: The length of the string stored at `key` after it was modified.
Examples:
>>> await client.set("key", "Hello World")
>>> await client.setrange("key", 6, "Redis")
11 # The length of the string stored at `key` after it was modified.
"""
return cast(
int,
await self._execute_command(
RequestType.SetRange, [key, str(offset), value]
),
)
async def mset(self, key_value_map: Mapping[str, str]) -> TOK:
"""
Set multiple keys to multiple values in a single atomic operation.
See https://redis.io/commands/mset/ for more details.
Note:
When in cluster mode, the command may route to multiple nodes when keys in `key_value_map` map to different hash slots.
Args:
key_value_map (Mapping[str, str]): A map of key value pairs.
Returns:
OK: a simple OK response.
Example:
>>> await client.mset({"key" : "value", "key2": "value2"})
'OK'
"""
parameters: List[str] = []
for pair in key_value_map.items():
parameters.extend(pair)
return cast(TOK, await self._execute_command(RequestType.MSet, parameters))
async def mget(self, keys: List[str]) -> List[Optional[str]]:
"""
Retrieve the values of multiple keys.
See https://redis.io/commands/mget/ for more details.
Note:
When in cluster mode, the command may route to multiple nodes when `keys` map to different hash slots.
Args:
keys (List[str]): A list of keys to retrieve values for.
Returns:
List[Optional[str]]: A list of values corresponding to the provided keys. If a key is not found,
its corresponding value in the list will be None.
Examples:
>>> await client.set("key1", "value1")
>>> await client.set("key2", "value2")
>>> await client.mget(["key1", "key2"])
['value1' , 'value2']
"""
return cast(
List[Optional[str]], await self._execute_command(RequestType.MGet, keys)
)
async def decr(self, key: str) -> int:
"""
Decrement the number stored at `key` by one. If the key does not exist, it is set to 0 before performing the
operation.
See https://redis.io/commands/decr/ for more details.
Args:
key (str): The key to increment its value.
Returns:
int: The value of key after the decrement.
Examples:
>>> await client.set("key", "10")
>>> await client.decr("key")
9
"""
return cast(int, await self._execute_command(RequestType.Decr, [key]))
async def decrby(self, key: str, amount: int) -> int:
"""
Decrements the number stored at `key` by `amount`. If the key does not exist, it is set to 0 before performing
the operation.
See https://redis.io/commands/decrby/ for more details.
Args:
key (str): The key to decrement its value.
amount (int) : The amount to decrement.
Returns:
int: The value of key after the decrement.
Example:
>>> await client.set("key", "10")
>>> await client.decrby("key" , 5)
5
"""
return cast(
int, await self._execute_command(RequestType.DecrBy, [key, str(amount)])
)
async def hset(self, key: str, field_value_map: Mapping[str, str]) -> int:
"""
Sets the specified fields to their respective values in the hash stored at `key`.
See https://redis.io/commands/hset/ for more details.
Args:
key (str): The key of the hash.
field_value_map (Mapping[str, str]): A field-value map consisting of fields and their corresponding values
to be set in the hash stored at the specified key.
Returns:
int: The number of fields that were added to the hash.
Example:
>>> await client.hset("my_hash", {"field": "value", "field2": "value2"})
2 # Indicates that 2 fields were successfully set in the hash "my_hash".
"""
field_value_list: List[str] = [key]
for pair in field_value_map.items():
field_value_list.extend(pair)
return cast(
int,
await self._execute_command(RequestType.HSet, field_value_list),
)
async def hget(self, key: str, field: str) -> Optional[str]:
"""
Retrieves the value associated with `field` in the hash stored at `key`.
See https://redis.io/commands/hget/ for more details.
Args:
key (str): The key of the hash.
field (str): The field whose value should be retrieved.
Returns:
Optional[str]: The value associated `field` in the hash.
Returns None if `field` is not presented in the hash or `key` does not exist.
Examples:
>>> await client.hset("my_hash", "field")
>>> await client.hget("my_hash", "field")
"value"
>>> await client.hget("my_hash", "nonexistent_field")
None
"""
return cast(
Optional[str],
await self._execute_command(RequestType.HGet, [key, field]),
)
async def hsetnx(
self,
key: str,
field: str,
value: str,
) -> bool:
"""
Sets `field` in the hash stored at `key` to `value`, only if `field` does not yet exist.
If `key` does not exist, a new key holding a hash is created.
If `field` already exists, this operation has no effect.
See https://redis.io/commands/hsetnx/ for more details.
Args:
key (str): The key of the hash.
field (str): The field to set the value for.
value (str): The value to set.
Returns:
bool: True if the field was set, False if the field already existed and was not set.
Examples:
>>> await client.hsetnx("my_hash", "field", "value")
True # Indicates that the field "field" was set successfully in the hash "my_hash".
>>> await client.hsetnx("my_hash", "field", "new_value")
False # Indicates that the field "field" already existed in the hash "my_hash" and was not set again.
"""
return cast(
bool,
await self._execute_command(RequestType.HSetNX, [key, field, value]),
)
async def hincrby(self, key: str, field: str, amount: int) -> int:
"""
Increment or decrement the value of a `field` in the hash stored at `key` by the specified amount.
By using a negative increment value, the value stored at `field` in the hash stored at `key` is decremented.
If `field` or `key` does not exist, it is set to 0 before performing the operation.
See https://redis.io/commands/hincrby/ for more details.
Args:
key (str): The key of the hash.
field (str): The field in the hash stored at `key` to increment or decrement its value.
amount (int): The amount by which to increment or decrement the field's value.
Use a negative value to decrement.
Returns:
int: The value of the specified field in the hash stored at `key` after the increment or decrement.
Examples:
>>> await client.hincrby("my_hash", "field1", 5)
5
"""
return cast(
int,
await self._execute_command(RequestType.HIncrBy, [key, field, str(amount)]),
)
async def hincrbyfloat(self, key: str, field: str, amount: float) -> float:
"""
Increment or decrement the floating-point value stored at `field` in the hash stored at `key` by the specified
amount.
By using a negative increment value, the value stored at `field` in the hash stored at `key` is decremented.
If `field` or `key` does not exist, it is set to 0 before performing the operation.
See https://redis.io/commands/hincrbyfloat/ for more details.
Args:
key (str): The key of the hash.
field (str): The field in the hash stored at `key` to increment or decrement its value.
amount (float): The amount by which to increment or decrement the field's value.
Use a negative value to decrement.
Returns:
float: The value of the specified field in the hash stored at `key` after the increment as a string.
Examples:
>>> await client.hincrbyfloat("my_hash", "field1", 2.5)
"2.5"
"""
return cast(
float,
await self._execute_command(
RequestType.HIncrByFloat, [key, field, str(amount)]
),
)
async def hexists(self, key: str, field: str) -> bool:
"""
Check if a field exists in the hash stored at `key`.
See https://redis.io/commands/hexists/ for more details.
Args:
key (str): The key of the hash.
field (str): The field to check in the hash stored at `key`.
Returns:
bool: Returns 'True' if the hash contains the specified field. If the hash does not contain the field,
or if the key does not exist, it returns 'False'.
Examples:
>>> await client.hexists("my_hash", "field1")
True
>>> await client.hexists("my_hash", "nonexistent_field")
False
"""
return cast(
bool, await self._execute_command(RequestType.HExists, [key, field])
)
async def hgetall(self, key: str) -> Dict[str, str]:
"""
Returns all fields and values of the hash stored at `key`.
See https://redis.io/commands/hgetall/ for details.
Args:
key (str): The key of the hash.
Returns:
Dict[str, str]: A dictionary of fields and their values stored in the hash. Every field name in the list is followed by
its value.
If `key` does not exist, it returns an empty dictionary.
Examples:
>>> await client.hgetall("my_hash")
{"field1": "value1", "field2": "value2"}
"""
return cast(
Dict[str, str], await self._execute_command(RequestType.HGetAll, [key])
)
async def hmget(self, key: str, fields: List[str]) -> List[Optional[str]]:
"""
Retrieve the values associated with specified fields in the hash stored at `key`.
See https://redis.io/commands/hmget/ for details.
Args:
key (str): The key of the hash.
fields (List[str]): The list of fields in the hash stored at `key` to retrieve from the database.
Returns:
List[Optional[str]]: A list of values associated with the given fields, in the same order as they are requested.
For every field that does not exist in the hash, a null value is returned.
If `key` does not exist, it is treated as an empty hash, and the function returns a list of null values.
Examples:
>>> await client.hmget("my_hash", ["field1", "field2"])
["value1", "value2"] # A list of values associated with the specified fields.
"""
return cast(
List[Optional[str]],
await self._execute_command(RequestType.HMGet, [key] + fields),
)
async def hdel(self, key: str, fields: List[str]) -> int:
"""
Remove specified fields from the hash stored at `key`.
See https://redis.io/commands/hdel/ for more details.
Args:
key (str): The key of the hash.
fields (List[str]): The list of fields to remove from the hash stored at `key`.
Returns:
int: The number of fields that were removed from the hash, excluding specified but non-existing fields.
If `key` does not exist, it is treated as an empty hash, and the function returns 0.
Examples:
>>> await client.hdel("my_hash", ["field1", "field2"])
2 # Indicates that two fields were successfully removed from the hash.
"""
return cast(int, await self._execute_command(RequestType.HDel, [key] + fields))
async def hlen(self, key: str) -> int:
"""
Returns the number of fields contained in the hash stored at `key`.
See https://redis.io/commands/hlen/ for more details.
Args:
key (str): The key of the hash.
Returns:
int: The number of fields in the hash, or 0 when the key does not exist.
If `key` holds a value that is not a hash, an error is returned.
Examples:
>>> await client.hlen("my_hash")
3
>>> await client.hlen("non_existing_key")
0
"""
return cast(int, await self._execute_command(RequestType.HLen, [key]))
async def hvals(self, key: str) -> List[str]:
"""
Returns all values in the hash stored at `key`.
See https://redis.io/commands/hvals/ for more details.
Args:
key (str): The key of the hash.
Returns:
List[str]: A list of values in the hash, or an empty list when the key does not exist.
Examples:
>>> await client.hvals("my_hash")
["value1", "value2", "value3"] # Returns all the values stored in the hash "my_hash".