Dragonfly Cloud is now available in the AWS Marketplace - learn more

Python: Redis Get Keys Without TTL (Detailed Guide w/ Code Examples)

Use Case(s)

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.

Code Examples

In Python with the redis-py library, you can get all keys without an associated TTL as follows:

import redis # Establish connection r = redis.Redis(host='localhost', port=6379, db=0) # Get all keys in the database all_keys = r.keys() # Filter out those with any TTL value set keys_without_ttl = [key for key in all_keys if r.ttl(key) == -1]

This script first fetches all keys in the Redis instance, then filters them by checking the TTL of each key. If ttl(key) returns -1, there is no expiry for that key.

Best Practices

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.

Common Mistakes

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'.

FAQs

**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.

Was this content helpful?

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost