GivP
GivP

Reputation: 2654

memcache and wildcards

I'm just wondering if there is a way to clear memcache using wildcards for key values.

So say I have a cache with the key "1234~foo" and another "1234~foo~bar".

Is there any way I can say clear the cache by using something like clear("1234*") and have it clear both from above?

I hope that makes sense.

Thanks.

Upvotes: 33

Views: 30141

Answers (4)

You Old Fool
You Old Fool

Reputation: 22941

How about this function in php:

function deleteKeysByIndex($search) {
    $m = new Memcached();
    $m->addServer('localhost', 11211);
    $keys = $m->getAllKeys();
    foreach ($keys as $index => $key) {
        if (strpos($key,$search) !== false) {
            $m->delete($key);
        } else {
            unset($keys[$index]);
        }
    }

    // returns an array of keys which were deleted
    return $keys;
}

Deletes keys beginning with $prefix and returns a list of all keys removed. I ran this on 30,000+ keys just now on a shared server and it was pretty quick - probably less than one second.

Upvotes: 2

Eric Petroelje
Eric Petroelje

Reputation: 60498

No, there isn't a direct easy way to do this. The FAQ addresses this, and provides a kind of workaround:

Deleting by Namespace

While memcached does not support any type of wildcard deleting or deletion by namespace (since there are not namespaces), there are some tricks that can be used to simulate this. They do require extra trips to the memcached servers however.

Example, in PHP, for using a namespace called foo:

$ns_key = $memcache->get("foo_namespace_key");
// if not set, initialize it
if($ns_key===false) {
    $ns_key=rand(1, 10000);
    $memcache->set("foo_namespace_key", $ns_key);
}
// cleverly use the ns_key
$my_key = "foo_".$ns_key."_12345";
$my_val = $memcache->get($my_key);

//To clear the namespace do:
$memcache->increment("foo_namespace_key");

Upvotes: 52

ksvendsen
ksvendsen

Reputation: 494

A note regarding the namespace solution by Eric Petroelje:

Remember that you don't know when memcached will evict you namespace key. Memcache might evict you namespace key, and then when trying to set a new key, it has a probability to 1 to 10000, that it will select the same index key - which means you will get "dirty" results. This is unlikely, but bottom line, it is not secure.

Same problem is with the solution by Poul Vernon.

A safe solution, will to be to use reliable storage (e.g. disk) for the "pointer key"/"namespace key".

Upvotes: 7

Paul Vernon
Paul Vernon

Reputation: 57

Create a memcache entry for "1234" and within it store an array of the associated keys. On your delete routine read and iterate through those keys to delete.

Upvotes: 0

Related Questions