28

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?

Christoffer
  • 7,436
  • 4
  • 40
  • 42
  • Unfortunately, it's not possible. But you can delete Redis keys according to the data associated in them. – Leonid Beschastny May 13 '13 at 10:13
  • @LeonidBeschastny Thanks. Is it because keys are not stored in a sorted way or saved with a date? – Christoffer May 13 '13 at 11:04
  • 4
    There is no way to get the time of keys creation unless you store it yourself in the data associated with it. As for the oldest keys, Redis optimized for fast key-value access, so it stores its data as a hash table. – Leonid Beschastny May 13 '13 at 11:20

4 Answers4

33

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)
Saverio Proto
  • 1,085
  • 9
  • 20
16

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

Dave Albert
  • 1,429
  • 15
  • 21
7

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

Gonzalo
  • 1,126
  • 2
  • 12
  • 21
4

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.

ptz0n
  • 461
  • 3
  • 14