Christoffer
Christoffer

Reputation: 7943

Redis: How to delete all keys older than 3 months

I want to flush out all keys older than 3 months. These keys were not set with an expire date.

Or if that is not possible, can I then delete maybe the oldest 1000 keys?

Upvotes: 29

Views: 49132

Answers (5)

Hany Sakr
Hany Sakr

Reputation: 2909

I use this command to clear all old entries after specific idle time, this example try to expire any idle key that has no access more than 180 seconds.

redis-cli -u rediss://HOST:6379 keys "*" | while read LINE;do if [ `redis-cli -u rediss://HOST:6379 object idletime "$LINE"` -gt 180 ];then `redis-cli -u rediss://HOST:6379 expire "$LINE" 1`;fi;done;

You can change the matching pattern or customize it as per your requirements with TTL for example.

Hope it could help!

Upvotes: 0

Saverio Proto
Saverio Proto

Reputation: 1145

Using the object idletime you can delete all keys that have not been used since three months. It is not exactly what you ask. If you created a key 6 months ago, but the key is accessed everyday, then idletime is updated and this script will not delete it. I hope the script can help:

#!/usr/bin/env python
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
for key in r.scan_iter("*"):
    idle = r.object("idletime", key)
    # idle time is in seconds. This is 90days
    if idle > 7776000:
        r.delete(key)

Upvotes: 38

Dave Albert
Dave Albert

Reputation: 1479

Are you NOW using an expire? If so, you could loop through all keys if no TTL is set then add one.

Python example:

for key in redis.keys('*'):
    if redis.ttl(key) == -1:
        redis.expire(key, 60 * 60 * 24 * 7)
        # This would clear them out in a week

EDIT As @kouton pointed out use scan over keys in production, see a discussion on that at: SCAN vs KEYS performance in Redis

Upvotes: 17

Gonzalo
Gonzalo

Reputation: 1146

A bit late, but check out the OBJECT command. There you will find object idle time (with 10 second resolution). It's used for debugging purposes but still, could be a nice workaround for your need.

References: http://redis.io/commands/object

Upvotes: 8

ptz0n
ptz0n

Reputation: 481

Sorry, that's not possible, as stated in the comments above. In Redis it's crucial to create your own indexes to support your access patterns.

Tip: What you should do is to create a sorted set (ZADD) with all new or modified keys, and set the score to a timestamp. This way you can with ease fetch the keys within a time period using ZRANGEBYSCORE.

If you want to expire your existing keys, get all keys (expensive) and set a TTL for each using the EXPIRE command.

Upvotes: 5

Related Questions