Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a key pattern in redis hash?

Tags:

python

redis

I have a hash table whose keys are of pattern USER_TEL like:

bob_123456  : Some address
mary_567894 : other address
john_123456 : third address

Now, I'd like to get addresses of all uses who have the same TEL in their keys.

What I came up with is:

tel = 123456
r.hmget('address_book', '*_%s' % tel)

I get [None] instead of the values.

like image 432
Jand Avatar asked Mar 07 '16 17:03

Jand


1 Answers

You should use HSCAN command.

For example:

redis> HMSET address_book bob_123456 Address1 mary_567894 Address2 john_123456 Address3
OK
redis> HSCAN address_book 0 match *_123456
1) "0"
2) 1) "bob_123456"
   2) "Address1"
   3) "john_123456"
   4) "Address3"

Update

Python implementation:

r = Redis(....) #redis url
for address in r.hscan_iter('address_book', match='*_123456'):
  print(address)
like image 182
thepirat000 Avatar answered Oct 19 '22 18:10

thepirat000