Abhijit Sarkar
Abhijit Sarkar

Reputation: 24618

Count the number of keys that start with string

I've two different types of keys saved, one prefixed with response, and another uuid. I want to count the number of keys that start with uuid. According to this answer, it's possible to filter keys using MATCH but is it possible to get a count?

Upvotes: 0

Views: 1389

Answers (1)

slorello
slorello

Reputation: 1159

There's no operation in Redis to get a count given a particular prefix. Here are a couple of ideas for you:

  1. If you're only storing Strings, you can use a Hash instead to keep track of everything, in this case, your UUID's would be fields in the hash rather than strings, but they are effectively equivalent. This would permit you to use the HLEN Command to see how many UUIDs you have. This would effectively be an O(1) solution - and has the added benefit of not relying on a separate counter key
  2. Keep a uuid_coutner key, whenever a new UUID is added just use INCR, if one is removed, simply use DECR. Can use INCRBY/DECRBY if you add/remove more than 1 at a time. This would effectively be an O(1) solution, but of course, the counter/keys are stored independently from each other.
  3. You can of course use the post you alluded to (a scan over all of your keys) to count them as well, but that is both O(n) and will incur a lot of unecessary traffic.

Upvotes: 2

Related Questions