How can I find the count of all the keys that has a matching pattern.
For example, there are two keys abc:random-text-1
and abc:random-text-2
. The common pattern here isabc:
. So, here the count is 2.
How can I do this in redis?
How can I find the count of all the keys that has a matching pattern.
For example, there are two keys abc:random-text-1
and abc:random-text-2
. The common pattern here isabc:
. So, here the count is 2.
How can I do this in redis?
If it's a one-time thing, you can use KEYS as described by x_maras, but you shouldn't use that in your code since KEYS will scan every key in the entire database each time it's called.
If you want to do it frequently, there is no "good" way exactly as you've written because it will always be fairly inefficient to scan every key (even using SCAN, since it would be doing the same thing as KEYS just in a safer manner).
However, if the patterns you need are known ahead of time, you can keep a set of every key that matches the pattern.
DISCLAIMER I hope this old answer haven't damaged any production systems, with millions of keys. If you still want to still count the matching keys of redis in production for some reason, better use scan with a match pattern.
If you simply search with KEYS, with your redis client, you will get a number list of all you matching keys, right?
e.g.
will give you
or you can run the following:
and you will get
2
as an output.From here:
It's not O(1), but at least the count is done on the server side.
By considering the performance, I would not recommend you use
KEYS
I would suggest you considering scan, if your redis version > 2.8.0. But it rely on which data type you are going to use.
Here is an simple example from redis doc:
From the command line,
redis-cli --scan --pattern 'abc:*' | wc -l