pantheon-systems / wp-redis

WordPress Object Cache using Redis.
https://wordpress.org/plugins/wp-redis/
GNU General Public License v2.0
226 stars 68 forks source link

Delete with wildcard? #305

Closed vincent-lu closed 3 years ago

vincent-lu commented 3 years ago

Hi as far as I understand WordPress itself doesn't have support to delete multiple object cache records with wildcard. But with my setup I'd greatly benefit from the ability to delete multiple object cache records with wildcard.

The situation is something like:

  1. I have multiple object cache records tied to a post_id (e.g. post_ID_meta_1, post_ID_meta_2, post_ID_meta_3, ....)
  2. I want to delete all object cache with keys matching post_ID_meta_*

Any suggestions on how to go about implementing this with wp-redis?

Thanks!

danielbachhuber commented 3 years ago

Hi @vincent-lu,

Have you explored the Redis hashes feature (briefly documented in Installation https://github.com/pantheon-systems/wp-redis#installation) ?

There are two ways to enable it:

  1. For all cache groups, with define( 'WP_REDIS_USE_CACHE_GROUPS', true );
  2. For specific cache groups, with wp_cache_add_redis_hash_groups( [ 'hash-group-name', 'other-hash-group-name' ] );

You'll probably want to start with the latter. Hash groups don't support expiry, so you might have unintended consequences if you enable it globally.

Once you've enabled hash groups for a specific group, you can:

wp_cache_set( 'foo', 'bar', 'hash-group-name' );
// Later on...
wp_cache_delete_group( 'hash-group-name' );

Let me know what you think!

vincent-lu commented 3 years ago

Hey @danielbachhuber thanks for the reply.

Specific cache groups could work, do you have any suggestions on where wp_cache_add_redis_hash_groups() should be defined? I imagine it's better to run wp_cache_add_redis_hash_groups() as early as possible?

What about dropping to the redis-cli level and run something like? redis-cli --scan --pattern post_ID_meta_* | xargs redis-cli UNLINK

danielbachhuber commented 3 years ago

Specific cache groups could work, do you have any suggestions on where wp_cache_add_redis_hash_groups() should be defined? I imagine it's better to run wp_cache_add_redis_hash_groups() as early as possible?

Yep, a mu-plugin is probably your best bet.

What about dropping to the redis-cli level and run something like? redis-cli --scan --pattern post_ID_meta_* | xargs redis-cli UNLINK

Eh, I suppose you could do something like that too. I'm not sure how the performance of that compares to hash groups but it's probably not a huge concern. The PHP implementation seems cleaner though.

vincent-lu commented 3 years ago

Thanks @danielbachhuber again, very much appreciated! Stay safe and merry xmas!