Search code examples
pythonrediskey-value-store

How to get indexed keys on a specific range in redis?


Using redis, let's say I have these keys with index on it:

user1:0
user1:1
user1:2
user1:3
user1:4
user2:0
user2:1
user2:2

How can I get the keys for let's say, user 1 from index 1-3? So, these are the results that I want:

user1:1
user1:2
user1:3

I tried these commands and got empty results:

LRANGE user1:* 1 4
SCAN user1:* CURSOR 1 COUNT 3

Another question: will it be better for me to save the index as an element in the secondary key?


Solution

  • You incorrectly used SCAN command.

    SCAN 0 MATCH user1:[1-3]
    

    Check the doc for detail.

    Another question: will it be better for me to save the index as an element in the secondary key?

    Yes, you can build a secondary index for keys matching the pattern, or try redisearch. When your data set is large, SCAN is inefficient.