Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis: possible to expire an element in an array or sorted set?

Tags:

caching

redis

People also ask

How does Redis expire?

When a key has an expire set, Redis will make sure to remove the key when the specified amount of time elapsed. The key time to live can be updated or entirely removed using the EXPIRE and PERSIST command (or other strictly related commands).

How do I expire a list in Redis?

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.

What does Redis use to sort the elements of a sorted set?

Redis Sorted Sets are similar to Redis Sets with the unique feature of values stored in a set. The difference is, every member of a Sorted Set is associated with a score, that is used in order to take the sorted set ordered, from the smallest to the greatest score.

How do I change the expiration date on Redis cache?

To create a Redis with an expiration time, use the SET command and the EX option to set the expiration time. The EX option takes a number in seconds and sets the number of seconds the key is valid until expiration. You can also use PX to specify the expiration time in Milliseconds.


There is a common pattern that solves this problem quite well.

Use sorted sets, and use a timestamp as the score. It's then trivial to delete items by score range, which could be done periodically, or only on every write, with reads always ignoring the out of range elements, by reading only a range of scores.

More here: https://groups.google.com/forum/#!topic/redis-db/rXXMCLNkNSs


Is it currently only possible to expire an entire key/value pair?

As far as I know, and also according to key commands and document about expiration, currently you can set expiration only to specific key and not to it's underlying data structure. However there is a discussion on google groups about this functionality with outlined alternative solutions.


I came upon a different method of handling this, don't know if it's helpful to any of you,but here goes:

The hash and the sorted set are linked by a guid.

  1. I have a hash that is set to expire in 'x' seconds
  2. I have a sorted set that is used for ranged queries
  3. The data for both is added in a transaction, so if one fails, they both fail.
  4. Upon a ranged query, use 'EXISTS' to see if the hashed value exists as the results are iterated over
  5. If it does not exist, it has expired, so delete the item from the sorted set