python – Storing keys with prefix that expire in redis

python – Storing keys with prefix that expire in redis

This cant be done directly. You can add an expiration on the hset as a whole, but not on individual fields. If you want to do this, you can call r.expire(name, time), where time is the number of seconds until expiration.

As an alternative, you can use set instead of hset:

for i in range(10):
    r.set(name: + str(i), i, ex=time_to_expire_s)

This will take away some functionality, since (for example) you wont have a good way to list all keys that start with name:, but it will let you set expirations for keys independently.

As a second option, you can set expirations in the values of the hset. This requires client side logic, and Redis wont do any expunging for you; but you could do something like:

for i in range(10):
    r.hset(
        name,
        i,
        json.dumps({ value: i, expiration: time.time() + time_to_expire_s })
    )

And then if you ever read a value whose expiration is in the past, you consider that to be a cache miss. This wont help you if youre trying to expire keys in order to free memory, but if your goal is to have the keys expire for some sort of correctness reason, this might work for you.

python – Storing keys with prefix that expire in redis

Leave a Reply

Your email address will not be published. Required fields are marked *