Search code examples
redisredis-3.2

Does a redis scan with a prefix match pattern scan all keys in database?


Let's say I have a redis instance with a million keys. The keys contain a team ID and a person ID and the values have some info about that team-person association. Example keys:

team:1:person:123
team:2:person:234
team:2:person:345
...

I could use a scan with a pattern to get all the people on a given team. For example, scan 0 match "team:123:person:*", would start getting everyone on team 123.

It sounds like this is not an efficient way to iterate over people in a team, because scan is O(N) where N is the number of keys in the database. But I want to confirm - is that the case?

A database with a tree index might only need to scan a small section of the tree, with keys with that prefix.

If it does scan everything, then I guess if I want to iterate quickly over people in a team, I need to store the set of person IDs under a team ID. Something like:

sset team:2:people 234 345 ...

Solution

  • But I want to confirm - is that the case?

    Confirmed, that is indeed the case.

    store the set of person IDs under a team ID

    That's exactly what you should. Mind, however, that once that Set grows too large doing SMEMBERS could be an expensive operation (hence impending the overall performance). If that indeed becomes an issue, use SSCAN to retrieve it leisurely-like instead.