Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of keys with value matching a pattern in redis-py?

How can I count number of keys with value matching a pattern in redis-py? I've found methods scan, scan_iter but they search using the pattern on the name of the key.

Example of what I need:

r = redis.Redis(host='localhost', port=6379, db=0)
r.set('key1', 'bar')
r.set('key2', 'bar')
r.set('key3', 'bar')
keys_num = len(list(r.unknown_scan(match='bar')))
print(keys_num)
>>3

I looked into documentation but could not find anything suitable. I thought about pulling all the keys and values and then loop them one by one counting values matching my pattern, but it looks inefficient, there should be a better way.

like image 279
Victor Di Avatar asked Dec 06 '25 08:12

Victor Di


1 Answers

What you suggested is the only possible solution. That said, if the value you are filtering by is a number, you might be able to eke out some performance benefits by using sorted sets and ZRANK. With redis, keyspace organization is the name of the game.

like image 152
dizzyf Avatar answered Dec 07 '25 22:12

dizzyf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!