Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete keys using regex in memcache

Tags:

memcached

Can i delete multiple keys in one go having similar key name in memcache using regex?

e.g. keys are:

key1
key2
key3

command [key.]

What "command" to use which should delete all of key1, key2, and key3?

like image 445
shadow3 Avatar asked Dec 06 '17 12:12

shadow3


1 Answers

Memcached does not have an option to delete keys with regex. You can delete cached data per key, or flush the whole cache.

If you have similar keys, you might look at official wiki for Memcached namspacing.

e.g. instead of having your keys in Memcached saved in like this:

key1
key2
key3

you could organize keys in namespaces, they would now look like this:

key:<namespace_value>:1
key:<namespace_value>:2
key:<namespace_value>:3

where namespace_value is some random integer, which you would keep in Memcached as well, per cache region (with prefix "key" ) For example, if your cache data looks like this:

<key>            <value>
namespace:key       1234
key:1234:1        value1
key:1234:2        value2
key:1234:3        value3

Now before you access your key, you will fetch the namespace_value first, and append it to your key.

  • Fetch value for namespace:key (results in 1234)
  • Fetch the value for key1 within namespace; your actual lookup key would be key:<namespace_value>:1 => key:1234:1

Now to evict all keys with prefix "key" it is sufficient to increment namespace_value, and save it back in your cache. Now your namespace value would be 1235, and cache data will be:

<key>            <value>
namespace:key      1235
key:1234:1        value1
key:1234:2        value2
key:1234:3        value3

The next fetch for key1 with the new namespace value will search for key:1235:1, and will give you a miss. Therefore, you have evicted the cache for all your keys.

like image 162
Igor Avatar answered Sep 23 '22 20:09

Igor