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?
The first command you can use to get the total number of keys in a Redis database is the DBSIZE command. This simple command should return the total number of keys in a selected database as an integer value.
To list the keys in the Redis data store, use the KEYS command followed by a specific pattern. Redis will search the keys for all the keys matching the specified pattern. In our example, we can use an asterisk (*) to match all the keys in the data store to get all the keys.
Redis SCAN SCAN is a cursor-based iteration command, allowing a client to go over all the elements in a table. This cursor-based scanner accepts an integer cursor on each call, and returns a batch of items and the cursor value to be used in the next call to SCAN.
From here:
eval "return #redis.pcall('keys', 'abc:*')" 0
It's not O(1), but at least the count is done on the server side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With