skip to Main Content

I need to get all the keys by prefix of the range of 62-125 and followed by ‘:’

Iv’e tried running the following with no success:

res = r.keys('[62-125]:*')

Also tried using scan:

iter = r.scan_iter('^(6[2-9]|7[0-9]):*')
res = []

for key in iter:
    res.append(key)

Is this even possible? if yes how?

Some examples incase it’s not clear:

Keys that should be retrieved:

62:kk:345345345
72:hg:76576
88:fg:67886
122:hg:8678
124:gg:8678

Keys that should NOT be retrieved:

0:df:09765
20:gg:6565
38:hh:345
44:bb:3454
61:bb:6568

All the keys in my DB are staring with a number prefix followed by ‘:’ if it matter.

3

Answers


  1. Chosen as BEST ANSWER

    A working solution:

    RES = []
    
    _res = r.keys('6[2-9]:*')
    RES.append(_res)
    
    for i in range(7,13):
        _res = r.keys('{}[0-9]:*'.format(i))
        RES.append(_res)
    

    This works but i do NOT accept this answer.

    1. It's disgusting and cause me self loathing
    2. It's not efficient at all

    I will vote down for my own solution if it was possible. Please suggest a better one.


  2. I would suggest you to use REDIS PIPELINE

    Like this…

    Pipeline pipelined = jedis.pipelined();
    for(keys : 62-125){
          pipelined.keys("keys*");
    }
    pipelined.sync();
    for(Reponse response : responses){
          Object o = response.get(); //Here you get the list of keys
    }
    

    You can’t use KEYS and SCAN to get keys for multiple match pattern.Refer this for more information

    Login or Signup to reply.
  3. Redis’ patterns (for KEYS and SCAN) are glob-like so trying to use regex on them is a no-go.

    You could use a server-side Lua script (with Lua having more robust pattern-matching capabilities, although not POSIX regex) that performs a full SCAN and filters the results.

    See https://stackoverflow.com/a/29945372/3160475 for an example.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search