Unable to delete multiple redis keys in nodejs using 'redis' package

Viewed 556

I have redis keys following a pattern like follows:

ZZprefixA-1
ZZprefixA-2
ZZprefixA-3
ZZprefixB-1
ZZprefixB-2
ZZprefixB-3
...

I want to all delete keys matching the following pattern

ZZprefixA-*

My code looks like following:

const redis = require('redis')
const { promisify } = require('util')

const options = {
  host: REDIS_HOST,
  port: REDIS_PORT,
  prefix: 'ZZ'
  password: REDIS_PASSWORD,
}

if (REDIS_PASSWORD) {
  options.password = REDIS_PASSWORD
}

const redisClient = redis.createClient(options)

delAsync = promisify(redisClient.del).bind(redisClient)
getKeysAsync = promisify(redisClient.keys).bind(redisClient)

Now I am trying to delete keys matching the pattern in following way:

const keys = await getKeysAsync(`ZZprefixA-*`)

const result = await delAsync(keys)

console.log(result)

const dkeys = await getKeysAsync(
      `ZZprefixA-*`
    )
console.log(dkeys)

The console log of 'result' prints 0, and 'dkeys' prints the matching keys despite having called del function on the keys.

1 Answers

The option prefix: 'ZZ' cause you problem, when you set key prefixA-1, redis will auto add prefix ZZ then the key become ZZprefixA-1. When you try del keys, redis will also add prefix ZZ to your geted keys ZZprefixA-1 ZZprefixA-2 ZZprefixA-3, then your real delete keys are ZZZZprefixA-1 ZZZZprefixA-2 ZZZZprefixA-3. While these keys is not exists, so nothing happens and your keys reserved.

Related