Algorithman
Algorithman

Reputation: 1334

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?

Upvotes: 0

Views: 1578

Answers (2)

for_stack
for_stack

Reputation: 22926

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.

Upvotes: 2

Dimitrios Mavrommatis
Dimitrios Mavrommatis

Reputation: 321

By reading the documentation for LRANGE it seems that the correct way to get your items would have been (assuming you use RPUSH to make the indexes):

redis> RPUSH user1 "one"
redis> RPUSH user1 "two"
redis> RPUSH user1 "three"
redis> RPUSH user1 "four"
redis> LRANGE user1 1 4
1) "one"
2) "two"
3) "three"
4) "four"

source

Upvotes: 0

Related Questions