skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search