How to delete items with same prefix key in memcached?

northtree picture northtree · May 29, 2012 · Viewed 29.4k times · Source

For example, I have some cached items with same prefix, such as

'app_111111', 'app_222222', 'app_333333', ...

Can I remove such 'app_xxxxxx' items by any memcached commands?

Answer

ziad-saab picture ziad-saab · May 29, 2012

Memcached does not offer this functionality out of the box so you have to build it in yourself.

The way I solve this is by defining a prefix (or namespace) in my application for groups of keys. Any key that I set in memcached has that prefix before it. Whenever I want to "delete" stuff from Memcached, I just change the prefix. And whenever I want to lookup a key in Memcached, I add that prefix to it.

In your case, you could start by setting the prefix to, say, MyAppPrefix1, so your keys will be stored as MyAppPrefix1::app_333333, MyAppPrefix1::app_444444.

Later on when you want to "delete" these entries, set your application to use MyAppPrefix2. Then, when you try to get a key from Memcached called app_333333, it will look for MyAppPrefix2::app_333333 and will not find it the first time around, as if it had been deleted.