I'm looking for a way to store a list of items for a user, that will expire within 24 hours. Is there a way to accomplish this using Redis? I was thinking of just using the list and setting an expiration for each individual item, is there a better way?
As noted in the accepted answer, expiration in Redis is only performed at key-level - nested elements cannot be expired. To "expire" items, call ZREMRANGEBYSCORE from -inf and the current epoch minus 24 hours.
After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology. The timeout will only be cleared by commands that delete or overwrite the contents of the key, including DEL , SET , GETSET and all the *STORE commands.
Redis TTL command is used to get the remaining time of key expiry in seconds. Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset.
Hi, it is not possible, either use a different top-level key for that specific field, or store along with the filed another field with an expire time, fetch both, and let the application understand if it is still valid or not based on current time.
As noted in the accepted answer, expiration in Redis is only performed at key-level - nested elements cannot be expired.
To implement a list with expiring elements, you can use the Sorted Set data structure. Every member's score should be the current epoch, so you'll retain the order of insertion. If the values (members) aren't unique, make them so by concatenating the epoch, e.g.:
ZADD user1:items 1514822755 1514822755:value
ZADD user1:items 1514822758 1514822758:value
To "expire" items, call ZREMRANGEBYSCORE
from -inf
and the current epoch minus 24 hours.
NO, you CANNOT set expiration for each item in a LIST
. You can only set an expiration for the entire LIST
.
In order to achieve what you want, you need to have a key for each item:
SET user1:item1 value EX 86400
SET uesr1:iter2 value EX 86400
SET user2:item1 value EX 86400
To get all items of a specified user, you can use the SCAN
command with a pattern (or use the Keyspace Notification
to achieve better performance, but with more complex work):
SCAN 0 MATCH user1:*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With