0
# Basic Operations
1
2
Core Redis operations for strings, numeric values, and key management. These fundamental commands form the foundation of most Redis applications and provide essential data storage and retrieval functionality.
3
4
## Capabilities
5
6
### String Operations
7
8
Basic string operations for storing and retrieving text and binary data with optional expiration and conditional operations.
9
10
```python { .api }
11
async def get(name: str) -> Optional[str]:
12
"""
13
Get the string value of a key.
14
15
Args:
16
name: The key name
17
18
Returns:
19
The key value or None if key doesn't exist
20
"""
21
22
async def set(
23
name: str,
24
value: Any,
25
ex: Optional[int] = None,
26
px: Optional[int] = None,
27
nx: bool = False,
28
xx: bool = False,
29
keepttl: bool = False,
30
get: bool = False
31
) -> Union[bool, Optional[str]]:
32
"""
33
Set the string value of a key with optional parameters.
34
35
Args:
36
name: The key name
37
value: The value to set
38
ex: Expiration in seconds
39
px: Expiration in milliseconds
40
nx: Only set if key doesn't exist
41
xx: Only set if key exists
42
keepttl: Keep existing TTL
43
get: Return old value
44
45
Returns:
46
True if successful, or old value if get=True
47
"""
48
49
async def mget(keys: List[str]) -> List[Optional[str]]:
50
"""
51
Get multiple keys in a single operation.
52
53
Args:
54
keys: List of key names
55
56
Returns:
57
List of values in same order as keys
58
"""
59
60
async def mset(mapping: Dict[str, Any]) -> bool:
61
"""
62
Set multiple keys in a single operation.
63
64
Args:
65
mapping: Dictionary of key-value pairs
66
67
Returns:
68
True if successful
69
"""
70
71
async def append(key: str, value: str) -> int:
72
"""
73
Append value to existing string.
74
75
Args:
76
key: The key name
77
value: Value to append
78
79
Returns:
80
New string length
81
"""
82
83
async def strlen(name: str) -> int:
84
"""
85
Get the length of a string value.
86
87
Args:
88
name: The key name
89
90
Returns:
91
String length or 0 if key doesn't exist
92
"""
93
94
async def getrange(key: str, start: int, end: int) -> str:
95
"""
96
Get substring of string stored at key.
97
98
Args:
99
key: The key name
100
start: Start offset
101
end: End offset (-1 for end of string)
102
103
Returns:
104
Substring
105
"""
106
107
async def setrange(name: str, offset: int, value: str) -> int:
108
"""
109
Overwrite part of string at given offset.
110
111
Args:
112
name: The key name
113
offset: Byte offset
114
value: Value to write
115
116
Returns:
117
New string length
118
"""
119
```
120
121
### Expiration Operations
122
123
Commands for setting and managing key expiration with various time formats and precision levels.
124
125
```python { .api }
126
async def setex(name: str, time: int, value: Any) -> bool:
127
"""
128
Set key with expiration time in seconds.
129
130
Args:
131
name: The key name
132
time: Expiration in seconds
133
value: The value to set
134
135
Returns:
136
True if successful
137
"""
138
139
async def psetex(name: str, time_ms: int, value: Any) -> bool:
140
"""
141
Set key with expiration time in milliseconds.
142
143
Args:
144
name: The key name
145
time_ms: Expiration in milliseconds
146
value: The value to set
147
148
Returns:
149
True if successful
150
"""
151
152
async def setnx(name: str, value: Any) -> bool:
153
"""
154
Set key only if it doesn't exist.
155
156
Args:
157
name: The key name
158
value: The value to set
159
160
Returns:
161
True if key was set, False if key already exists
162
"""
163
164
async def msetnx(mapping: Dict[str, Any]) -> bool:
165
"""
166
Set multiple keys only if none exist.
167
168
Args:
169
mapping: Dictionary of key-value pairs
170
171
Returns:
172
True if all keys were set, False if any key exists
173
"""
174
```
175
176
### Numeric Operations
177
178
Atomic increment and decrement operations for numeric values with integer and floating-point support.
179
180
```python { .api }
181
async def incr(name: str, amount: int = 1) -> int:
182
"""
183
Increment key by amount.
184
185
Args:
186
name: The key name
187
amount: Amount to increment by
188
189
Returns:
190
New value after increment
191
"""
192
193
async def incrby(name: str, amount: int = 1) -> int:
194
"""
195
Increment key by integer amount.
196
197
Args:
198
name: The key name
199
amount: Integer amount to increment
200
201
Returns:
202
New value after increment
203
"""
204
205
async def incrbyfloat(name: str, amount: float = 1.0) -> float:
206
"""
207
Increment key by float amount.
208
209
Args:
210
name: The key name
211
amount: Float amount to increment
212
213
Returns:
214
New value after increment
215
"""
216
217
async def decr(name: str, amount: int = 1) -> int:
218
"""
219
Decrement key by amount.
220
221
Args:
222
name: The key name
223
amount: Amount to decrement by
224
225
Returns:
226
New value after decrement
227
"""
228
229
async def decrby(name: str, amount: int = 1) -> int:
230
"""
231
Decrement key by integer amount.
232
233
Args:
234
name: The key name
235
amount: Integer amount to decrement
236
237
Returns:
238
New value after decrement
239
"""
240
```
241
242
### Key Management
243
244
Essential key management operations for checking existence, deleting keys, setting expiration, and key introspection.
245
246
```python { .api }
247
async def exists(*names: str) -> int:
248
"""
249
Check how many keys exist.
250
251
Args:
252
names: Key names to check
253
254
Returns:
255
Number of existing keys
256
"""
257
258
async def delete(*names: str) -> int:
259
"""
260
Delete one or more keys.
261
262
Args:
263
names: Key names to delete
264
265
Returns:
266
Number of keys deleted
267
"""
268
269
async def unlink(*names: str) -> int:
270
"""
271
Asynchronously delete keys.
272
273
Args:
274
names: Key names to unlink
275
276
Returns:
277
Number of keys unlinked
278
"""
279
280
async def expire(name: str, time: int) -> bool:
281
"""
282
Set key expiration in seconds.
283
284
Args:
285
name: The key name
286
time: Expiration time in seconds
287
288
Returns:
289
True if expiration was set
290
"""
291
292
async def expireat(name: str, when: int) -> bool:
293
"""
294
Set key expiration at timestamp.
295
296
Args:
297
name: The key name
298
when: Unix timestamp
299
300
Returns:
301
True if expiration was set
302
"""
303
304
async def pexpire(name: str, time: int) -> bool:
305
"""
306
Set key expiration in milliseconds.
307
308
Args:
309
name: The key name
310
time: Expiration time in milliseconds
311
312
Returns:
313
True if expiration was set
314
"""
315
316
async def pexpireat(name: str, when: int) -> bool:
317
"""
318
Set key expiration at timestamp in milliseconds.
319
320
Args:
321
name: The key name
322
when: Unix timestamp in milliseconds
323
324
Returns:
325
True if expiration was set
326
"""
327
328
async def ttl(name: str) -> int:
329
"""
330
Get key time to live in seconds.
331
332
Args:
333
name: The key name
334
335
Returns:
336
TTL in seconds, -1 if no expiration, -2 if key doesn't exist
337
"""
338
339
async def pttl(name: str) -> int:
340
"""
341
Get key time to live in milliseconds.
342
343
Args:
344
name: The key name
345
346
Returns:
347
TTL in milliseconds, -1 if no expiration, -2 if key doesn't exist
348
"""
349
350
async def persist(name: str) -> bool:
351
"""
352
Remove key expiration.
353
354
Args:
355
name: The key name
356
357
Returns:
358
True if expiration was removed
359
"""
360
361
async def type(name: str) -> str:
362
"""
363
Get key data type.
364
365
Args:
366
name: The key name
367
368
Returns:
369
Key type string ('string', 'list', 'set', 'zset', 'hash', 'stream')
370
"""
371
```
372
373
### Key Pattern Operations
374
375
Operations for finding and working with keys using patterns, random key selection, and key renaming.
376
377
```python { .api }
378
async def keys(pattern: str = "*") -> List[str]:
379
"""
380
Find keys matching pattern.
381
382
Args:
383
pattern: Glob-style pattern (* and ? wildcards)
384
385
Returns:
386
List of matching key names
387
"""
388
389
async def scan(
390
cursor: int = 0,
391
match: Optional[str] = None,
392
count: Optional[int] = None,
393
_type: Optional[str] = None
394
) -> Tuple[int, List[str]]:
395
"""
396
Incrementally scan keys.
397
398
Args:
399
cursor: Scan cursor position
400
match: Pattern to match
401
count: Hint for keys per iteration
402
_type: Filter by key type
403
404
Returns:
405
Tuple of (next_cursor, keys)
406
"""
407
408
async def randomkey() -> Optional[str]:
409
"""
410
Get random key name.
411
412
Returns:
413
Random key name or None if database is empty
414
"""
415
416
async def rename(src: str, dst: str) -> bool:
417
"""
418
Rename key.
419
420
Args:
421
src: Source key name
422
dst: Destination key name
423
424
Returns:
425
True if successful
426
"""
427
428
async def renamenx(src: str, dst: str) -> bool:
429
"""
430
Rename key only if destination doesn't exist.
431
432
Args:
433
src: Source key name
434
dst: Destination key name
435
436
Returns:
437
True if key was renamed, False if destination exists
438
"""
439
```
440
441
### Bit Operations
442
443
Bitwise operations on string values for efficient bit-level data manipulation and storage.
444
445
```python { .api }
446
async def getbit(name: str, offset: int) -> int:
447
"""
448
Get bit value at offset.
449
450
Args:
451
name: The key name
452
offset: Bit offset
453
454
Returns:
455
Bit value (0 or 1)
456
"""
457
458
async def setbit(name: str, offset: int, value: int) -> int:
459
"""
460
Set bit value at offset.
461
462
Args:
463
name: The key name
464
offset: Bit offset
465
value: Bit value (0 or 1)
466
467
Returns:
468
Previous bit value
469
"""
470
471
async def bitcount(name: str, start: Optional[int] = None, end: Optional[int] = None) -> int:
472
"""
473
Count set bits in string.
474
475
Args:
476
name: The key name
477
start: Start byte offset
478
end: End byte offset
479
480
Returns:
481
Number of set bits
482
"""
483
484
async def bitpos(
485
key: str,
486
bit: int,
487
start: Optional[int] = None,
488
end: Optional[int] = None
489
) -> int:
490
"""
491
Find first bit position.
492
493
Args:
494
key: The key name
495
bit: Bit value to find (0 or 1)
496
start: Start byte offset
497
end: End byte offset
498
499
Returns:
500
First bit position or -1 if not found
501
"""
502
503
async def bitop(operation: str, dest: str, *keys: str) -> int:
504
"""
505
Perform bitwise operation between strings.
506
507
Args:
508
operation: Bitwise operation ('AND', 'OR', 'XOR', 'NOT')
509
dest: Destination key
510
keys: Source keys
511
512
Returns:
513
Length of destination key
514
"""
515
```
516
517
## Usage Examples
518
519
### Basic String Operations
520
521
```python
522
import aioredis
523
524
async def string_examples():
525
redis = aioredis.Redis(decode_responses=True)
526
527
# Basic set/get
528
await redis.set('user:1:name', 'John Doe')
529
name = await redis.get('user:1:name')
530
print(name) # "John Doe"
531
532
# Set with expiration
533
await redis.setex('session:abc123', 3600, 'session_data')
534
535
# Conditional set
536
created = await redis.setnx('counter', 0) # Only if doesn't exist
537
if created:
538
print("Counter initialized")
539
540
# Multiple operations
541
await redis.mset({'key1': 'value1', 'key2': 'value2', 'key3': 'value3'})
542
values = await redis.mget(['key1', 'key2', 'key3'])
543
print(values) # ['value1', 'value2', 'value3']
544
545
### Numeric Operations
546
547
```python
548
async def numeric_examples():
549
redis = aioredis.Redis(decode_responses=True)
550
551
# Initialize counter
552
await redis.set('page_views', 0)
553
554
# Increment operations
555
await redis.incr('page_views') # 1
556
await redis.incrby('page_views', 5) # 6
557
await redis.incrbyfloat('average_score', 2.5) # 2.5
558
559
# Decrement operations
560
await redis.decr('page_views') # 5
561
await redis.decrby('page_views', 2) # 3
562
563
current = await redis.get('page_views')
564
print(f"Current page views: {current}")
565
```
566
567
### Key Management
568
569
```python
570
async def key_management_examples():
571
redis = aioredis.Redis(decode_responses=True)
572
573
# Check key existence
574
exists = await redis.exists('user:1', 'user:2', 'user:3')
575
print(f"{exists} keys exist")
576
577
# Set expiration
578
await redis.expire('temp_key', 300) # 5 minutes
579
remaining = await redis.ttl('temp_key')
580
print(f"TTL: {remaining} seconds")
581
582
# Find keys by pattern
583
user_keys = await redis.keys('user:*')
584
print(f"Found {len(user_keys)} user keys")
585
586
# Scan for better performance with large datasets
587
cursor = 0
588
all_keys = []
589
while True:
590
cursor, keys = await redis.scan(cursor, match='session:*', count=100)
591
all_keys.extend(keys)
592
if cursor == 0:
593
break
594
595
# Key type inspection
596
key_type = await redis.type('user:1:name')
597
print(f"Key type: {key_type}")
598
```