'How to tag a key in REDIS so later I can remove all keys that match this tag?
Today we save data like that:
redisClient->set($uniquePageID, $data);
and output the data like that:
redisClient->get($uniquePageID)
But now we need to remove the data base on a userID. So we need something like that:
redisClient->set($uniquePageID, $data)->tag($userID);
So we can remove all the keys that related to this userID only, for example:
redisClient->tagDel($userID);
Does REDIS can solve something like that?
Thanks
Solution 1:[1]
There's no built-in way to do that. Instead, you need to tag these pages by yourself:
- When setting a page-data pair, also put the page id into a
SET
of the corresponding user. - When you want to remove all pages of a given user, scan the
SET
of the user to get the page ids of this user, and delete these pages.
When scanning the SET
, you can use either SMEMBERS
or SSCAN
command, depends on the size of the SET
. If it's a big SET
, prefer SSCAN
to avoid block Redis for a long time.
Solution 2:[2]
I used HSET and HDEL to store and delete items like this:
$this->client = new Predis\Client(array...);
$this->client->hset($key, $tag, $value);
$this->client->hdel($key, $tags)
and if you want to delete every item KEY no matter tag or value you can use del key, it works with any data type including hset
$this->client->del($key);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | for_stack |
Solution 2 | Caro Facchini |