Get all keys matching the pattern First try KEYS command, if not supported fallback to SCAN
(self, pattern: str)
| 75 | self._redis_client.set(key, pickle.dumps(value), ex=expire_time) |
| 76 | |
| 77 | def keys(self, pattern: str) -> List[str]: |
| 78 | """ |
| 79 | Get all keys matching the pattern |
| 80 | First try KEYS command, if not supported fallback to SCAN |
| 81 | """ |
| 82 | try: |
| 83 | # Try KEYS command first (faster for standard Redis) |
| 84 | return [key.decode() if isinstance(key, bytes) else key for key in self._redis_client.keys(pattern)] |
| 85 | except ResponseError as e: |
| 86 | # If KEYS is not supported (e.g., Redis Cluster or cloud Redis), use SCAN |
| 87 | if "unknown command" in str(e).lower() or "keys" in str(e).lower(): |
| 88 | keys_list: List[str] = [] |
| 89 | cursor = 0 |
| 90 | while True: |
| 91 | cursor, keys = self._redis_client.scan(cursor=cursor, match=pattern, count=100) |
| 92 | keys_list.extend([key.decode() if isinstance(key, bytes) else key for key in keys]) |
| 93 | if cursor == 0: |
| 94 | break |
| 95 | return keys_list |
| 96 | else: |
| 97 | # Re-raise if it's a different error |
| 98 | raise |
| 99 | |
| 100 | |
| 101 | if __name__ == '__main__': |
no outgoing calls