For example I have User:1
, User:2
, User:3
... User:2000
. I want to remove all User
so I can start fresh. Is there a way of doing this without knowing the exact keys just that I want to remove all keys with the User
domain? I'm interested in doing this as part of the startup task for the application server.
Asked
Active
Viewed 59 times
0

Cenoc
- 11,172
- 21
- 58
- 92
-
1possible duplicate of [How to atomically delete keys matching a pattern using Redis](http://stackoverflow.com/questions/4006324/how-to-atomically-delete-keys-matching-a-pattern-using-redis) – Mar 01 '15 at 17:30
-
@TimCooper the OP didn't specifically ask for atomicity, but in any case my answer at that thread provides the solution. – Itamar Haber Mar 01 '15 at 19:18
1 Answers
0
A better approach than using 'keys' to scan all the keys and remove by a regex match, would be to use a tagging mechanism, to maintain a Redis SET in the server that holds the relation Tag-Keys, like the one on this post: http://stackify.com/implementing-cache-tagging-redis/
I'm using a similar approach, this is the Lua Script I ended up using to set a key-value related to one or more tags:
local tagcount = 0
local cacheKey = KEYS[1]
local exp = ARGV[2]
local setValue = ARGV[1]
-- For each Tag, add the reference to the TagKey Set
for i=2,#KEYS do
local tag = ':tag:' .. KEYS[i]
local tagTtl = redis.call('ttl', tag)
tagcount = tagcount + redis.call('sadd', tag, cacheKey)
if(exp ~= nil and tagTtl ~= -1) then
-- Tag is volatile or was not found. Expiration provided. Set the Expiration.
redis.call('expire', tag, math.max(tagTtl, exp))
else
-- Tag is not volatile or the key to add is not volatile, mark the tag SET as not volatile
redis.call('persist', tag)
end
end
-- Set the cache key-value
if(setValue) then
if(exp ~= nil) then
redis.call('setex', cacheKey, exp, setValue)
else
redis.call('set', cacheKey, setValue)
end
end
return tagcount
Note the prepended ":tag:" to the keys that represents tags SETs.
If you don't need an atomic way to delete the keys by tag, you can do it with your Redis client in two operations, for example by getting the members of the tag "user" with SMEMBERS :tag:user
and removing the keys with the DEL key1 key2 ..
command.

thepirat000
- 12,362
- 4
- 46
- 72