I do store a lot of statistical data in Redis, storing
information on what users do and behave every day, week, month
and so on... But storing a huge amount of data in memory has a
little drawback: memory is cheap and fast, but is
finite.
From time to time (e.g: cron job) I need to clean up the
house because there is too much memory filled that is no longer
interesting to keep it. Maybe you are thinking now, why this
guy is not setting an EXPIRATION date? Well, I do.
Problem is that with early versions of Redis after the expiration
time a KEY won't be really deleted from memory until the
next access to the key, which never might happen. There
is also a random process that deletes keys and there was a change
of behaviour regarding expiration in Redis 2.2, read more on expiration here.
In my case, I do store keys using human-readable dates as part of
the key name, which I need to delete by pattern. To make it more
graphical with a similar example, imagine you are storing user
behavior in keys named like:
ub:2011-08-18:id-tracked-page...
Decomposing the elements:
- ub: user-behavior alias
- 2011-08-18: Stores all the events for August 18th
- id-tracked-page: Name or code of the page I want to
track (e.g: home)
- ... more constraints could be added
Then, I am not interested in last month's data (July) regarding
user behaviour so I can trigger in the terminal the following
command:
redis-cli -n 0 KEYS ub:2011-07-* | xargs redis-cli -n 0 DEL
This deletes all the redis keys based on this
pattern.
The output would produce something like:
$ redis-cli -n 0 KEYS ub:2011-07-* | xargs redis-cli -n 0 DEL
(integer) 188
(integer) 175
(integer) 191
(integer) 186
(integer) 153
You should notice that there is a -n 0 in the
command indicating to trigger the command in the DATABASE 0.
Since I do have many databases in a single server (multiple
database support will be removed soon) I do always specify it. If
you use a single database, just drop the "-n 0".
Also, you might need to surround by quotes the pattern part if
contains spaces or other unfriendly chars.
Hope this helps