Fetching keys from a Redis database without a set Time To Live (TTL) can be useful for understanding which data within your store may persist indefinitely. This could be helpful when debugging, or when trying to understand memory usage patterns.
In Python with the
redis-py library, you can get all keys without an associated TTL as follows:
This script first fetches all keys in the Redis instance, then filters them by checking the TTL of each key. If
-1, there is no expiry for that key.
When using the keys() function, be mindful that it can be slow on large databases, because it may block the server while retrieving the data. It's more efficient to use the SCAN command where possible.
A common mistake is to forget that the
ttl method returns
-1 both when the key does not exist and when the key has no associated TTL. Make sure the key exists before interpreting
-1 as 'no TTL set'.
**Q: What does a TTL of -1 mean in Redis? ** A: In Redis, a TTL (or time-to-live) value of -1 means that the key does not have an expiration time.
**Q: Is there a way to set default TTL for all keys in Redis? ** A: While Redis itself doesn't provide a built-in way to set a default TTL for all keys, you can implement this logic in your application. Ensure you set a TTL every time you create a new key.