Search code examples
redisredis-cli

Redis - delete field by pattern matching on hash key


I have the following structure in Redis,

commKey:hkey1
    target1 - value1
    target2 - value2
commKey:hkey2
    target2 - value3
    target3 - value4
commKey:hkey3
    target1 - value5
    target3 - value6
...

commkey will appear on all hashkeys followed by a namespace and a unique string(hkey1, hkey2, hkey3...). I want to remove all target1 s in all keys. target1 appears in commKey:hkey1 and commKey:hkey3. So, this is something like match commKey:* and del target1. I tried to do it with hscan which enables pattern match on subkeys(fields). But I need to do it on "haskkey". How to do it in an efficient way? Thanks in advance.

PS: We have commKey because in future we may want to add another type of hashkey which don't start with commKey and it should not be affected by this.


Solution

  • You should scan the keys, not the hash.

    1. Use SCAN command to get keys that match commKey:*
    2. For each key, call HDEL to remove the given target, no matter whether the hash has such a field or not.