Victor Di
Victor Di

Reputation: 1198

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.

Upvotes: 3

Views: 2492

Answers (1)

dizzyf
dizzyf

Reputation: 3693

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.

Upvotes: 1

Related Questions