I have the following piece of code that I am using to delete records from Redis
public hdel(hash: string, field?: string) {
return new Promise((resolve, reject) => {
if (!field) {
this.store.del(hash, (err, response) => {
if (err) {
reject(err);
return;
}
resolve(response);
});
return;
}
this.store.hdel(hash, field, (err, response) => {
if (err) {
reject(err);
return;
}
resolve(response);
});
});
}
If field is not given, I will be deleting all fields.
store
is just a RedisClient
.
I am using the Redis package
I am looking to delete all records that starts with the prefix I give, for example I have the following code:
async deleteSessionFiles(sessionId: string) {
const path = SessionPathResolver.resolveSessionAllFiles(sessionId);
await this.cacheService.hdel(path);
}
This piece of code generates a redis ALL record path by session ID by using *
at the end of the path, for example sessions/gHs46f/files/*
static resolveSessionAllFiles = (sessionId: string) => {
return `sessions/${sessionId}/files/*`;
}
and then I am using the function I provided at the beginning of the question.
However, unlike the KEYS prefix/*
command which knows to give you all records of a given prefix, this won’t delete all records, not even one.
What is the right way to do such operation with this package or in general?
2
Answers
You can use
Redis
SCAN
command to fetch keys by a curser and useDEL
to delete all fetched keys, and iterate it over the keys without bad effects ofKEYS *
Read more about
SCAN
command hereAnd Here an example of using
SCAN
inredis package
Also, see this question and its answers there is lots of good ways to delete in batch
Delete keys by pattern Redis nodejs