0

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?

ben berizovsky
  • 759
  • 1
  • 6
  • 17

2 Answers2

0

You can use Redis SCAN command to fetch keys by a curser and use DEL to delete all fetched keys, and iterate it over the keys without bad effects of KEYS *

Read more about SCAN command here

And Here an example of using SCAN in redis package

Also, see this question and its answers there is lots of good ways to delete in batch

Ali Malek
  • 578
  • 8
  • 26
  • There is no way to do this in one call? I knew of this way, however I thought there could be a more efficient approach to this? – ben berizovsky Oct 18 '21 at 13:54
  • @benberizovsky you can use `Lua` code like this [answer](https://stackoverflow.com/a/16974060/2882619) – Ali Malek Oct 18 '21 at 13:57
0

Delete keys by pattern Redis nodejs

 for await (const key of cacheConnection.scanIterator({
      TYPE: 'string', // `SCAN` only
      MATCH: `*${somekeypattern}*`,
      COUNT: 100
    })) {
      // use the key!
      await cacheConnection.del(key);
    }
Karunakaran
  • 385
  • 5
  • 16