cache.set("determ_" + str(id), cache_object)
Am working with Django cache using Redis, these are sample of my cache keys
determ_1ba243f3-2eda-4feb-bf24-1aa4c0cd2171
appr_hist_2bfd55e4-22c1-4cc3-a913-8ac2cde3801b
appr_act_5a18c351-e172-4369-9a4b-118c3df5b25a
but i get challenge when i want to delete cache using some part of key like determ_
, appr_hist_
, appr_act_
How will manage to accomplish this ?
from django.core.cache import cache
class CacheManager:
@classmethod
def delete_cache(self, prefixes = []):
for pattern in prefixes:
cache.delete(pattern)
return True
CacheManager.delete_cache(['determ_','appr_hist_', 'det_appr','appr_act_','deter_sect_'])
2
Answers
Thank you so much @Guy Royse for the great inputs. I use the idea and build this method and now it work fine thought i will need to deal with my policies and performance
I can’t speak for Django, but Redis doesn’t have a patterned delete feature. The way this is typically done works but it not performant.
It involves the use of the SCAN command to get all the keys that match a pattern. SCAN is an O(N) operation where N is the number of keys you have in Redis. Then, you issue an UNLINK on all of the fields. The UNLINK is variadic so you can pass in all the matching keys to it.
The KEYS and DEL commands will work as well but are even less performant. KEYS blocks Redis while it runs and other clients then can’t use Redis. DEL blocks Redis until the memory is freed while UNLINK returns and then frees the memory.
Not sure if you can get to any of these commands from Django, but I hope this helps.