Redis : Delete Keys by checking/matching expiry time remaining.
Sometimes we need to remove specific group of keys which are created earlier or have a specific expiry time remaining. You can simply delete Redis Key-value pairs by checking their expiry time remaining and running this simple script on your console:
redis-cli -h <hostname> keys “*” | while read LINE ; do TTL=`redis-cli -h <hostname> ttl $LINE`; if [ $TTL -ge <expiry-time-need-to-check> ]; then echo “del $LINE”; RES=`redis-cli -h <hostname> del $LINE`; fi; done;
Example:
# redis-cli -h 127.0.0.1 keys “*” | while read LINE ; do TTL=`redis-cli -h 127.0.0.1 ttl $LINE`; if [ $TTL -ge 40000 ]; then echo “del $LINE”; RES=`redis-cli -h 127.0.0.1 del $LINE`; fi; done;
You can also modify/use this script to delete PERSIST Keys(Non-Expiring Keys), which never get removed automatically.
# redis-cli -h 127.0.0.1 keys “*” | while read LINE ; do TTL=`redis-cli -h 127.0.0.1 ttl $LINE`; if [ $TTL -eq -1 ]; then echo “del $LINE”; RES=`redis-cli -h 127.0.0.1 del $LINE`; fi; done;










