Search code examples
redispattern-matchingglob

how to pattern match empty string in redis?


In Redis, I have hash keys in the following format

keys {
  'img::opt': 'nameX',
  'img:*:opt': 'nameY',
  'img:#:opt': 'nameZ',
  'img:A:opt': 'nameN'
}

It is actually in the format of 'extension:owner:spec'

I want to perform hscan based on owner which returns,

1. Everything except blank(will return 2nd, 3rd and 4th keys)
2. Only blank and star(*)(will return 1st and 2nd keys)

For first, I can use pattern as 'img:?*:opt'. How to write a pattern which can be used for 2nd case.

I tried,

img:[^][*]:opt
img:[^|*]:opt
img:[*^]:opt

But none of them are working. Is it possible to pattern match empty string?


Solution

  • Redis' glob-style pattern matching syntax doesn't support the not ('^') operator.

    However, as you're looking for two specific keys, why not access them directly by simply doing:

    HGET img:*:opt img::opt
    

    Note: in Redis versions prior to 4, HGET needs to be replaced with HMGET