Shift Redis keys

47 Views Asked by At

In my Redis DB, I've got a list of keys saved in a format of prefix:<index>, so the sample DB looks like this:

prefix:0 = "lorem"
prefix:1 = "ipsum"
prefix:2 = "dolor"
prefix:3 = "sit"

The problem is when I try to delete prefix:1, because I need the ipsum gone for whatever reason, I'm left with a gap between indexes – the DB being like this:

prefix:0 = "lorem"
prefix:2 = "dolor"
prefix:3 = "sit"

And I need the DB to be like this:

prefix:0 = "lorem"
prefix:1 = "dolor"
prefix:2 = "sit"

How do I shift the indexes of keys to fill the gap (shifting prefix:2 to prefix:1 and prefix:3 to prefix:2) in Python with the redis-py library? All I can think of is looping through all keys with index greater than deleted index and rename them, but I'd prefer a bulk solution, if there's any.

1

There are 1 best solutions below

4
Aravind Kannan On

I'm not completely sure of what you are trying to solve here exactly by using redis and shifting keys inside of it. You could just delete prefix:3 rather than deleting prefix:1 and then shifting the remaining keys. I am not sure what I'm missing, please do add more clarity to your question.

Operation :  DELETE `prefix:1` and SHIFT <=> DELETE `prefix:3`
Input     : `prefix:0` `prefix:1` `prefix:2` `prefix:3`
Output    : `prefix:0` `prefix:1` `prefix:2`