Remove a member from multiple sets in Redis

524 views Asked by At

There are products and categories in my redis storage. I'm using categories sets to find products by specified category.

SADD category:1 product1 product2 product3 product4
SADD category:2 product2 product5
SADD category:5 product1 product7

Is there any way to remove a single product from all the categories except iterating over all of them? Eg some magic like this:

SREM category:* product2
1

There are 1 answers

0
Itamar Haber On

There's no magic command.

What you could do is use (yet another) Set to track the category Sets for each product. For example, in your example you'd have to do:

SADD product2:categories category:1 category:2

And then for each of that Set's members (SMEMBERS or SSCAN to get them), do an SREM for the product from that category.

Note that while this appears to be a perfect candidate for a Lua script, it is in fact not. This is because you'd be modifying keys (the categories' Sets) without explicitly providing their names via the KEYS input construct, a shunned-upon practice that will render said script non-cluster-compatible.