Unfortunately, there is no direct method in Redis to fetch keys based on their TTL. We can however achieve it by iterating over all the keys and checking their TTL.
Example:
const redis = require('redis'); const client = redis.createClient(); client.keys('*', (err, keys) => { keys.forEach(key => { client.ttl(key, (err, ttl) => { if(ttl === 'your_desired_ttl') { // Replace 'your_desired_ttl' with the desired TTL value console.log(key); } }); }); });
In this code, we first get all the keys using keys('*')
. Then for each key, we get the TTL using ttl(key)
function. If the TTL equals our desired TTL, we print out the key.
KEYS
command in production environment because it may affect performance. Instead, use SCAN
command which is safer for production.Q: Can I get keys directly using their TTL in Redis?
A: No, Redis does not support getting keys directly based on their TTL. You have to iterate over keys and check TTL for each key.
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.