0

In a hash, I have a bunch of keys-values pairs

my keys are in the following format: name:city

john:newyork
kate:chicago
lisa:atlanta

Im using python to access redis and in https://redis-py.readthedocs.org/en/latest/, i dont see any hash operations that does the partial matching

i would like to be able to get all keys in the hash with a city name

is that possible?

ealeon
  • 12,074
  • 24
  • 92
  • 173

2 Answers2

1

It is possible, but not with HASH objects, but with sorted sets. As long as all elements in a sorted set have the same score, you can do lexicographical prefix matching.

let's say you do the following (raw redis commands, but the same applies with the python client):

ZADD foo 0 john:newyork:<somevalue>
ZADD foo 0 john:chicago:<somevalue>
ZADD foo 0 kate:chicago:<somevalue>
....

You can then query by using ZRANGEBYLEX:

ZRANGEBYLEX foo [john: (john:\xff

will give you all entries that start with john, and you can extract the value with regular expressions or splitting.

Note that this is a prefix search and not suffix search. if you want "all entries in new york" you need to reverse the order in the sorted set.

Not_a_Golfer
  • 47,012
  • 14
  • 126
  • 92
  • hmm i would still like to have O(1) on lookup (in other cases when i dont have to look by partial key) so i guess i can have both sorted set along with hash. is this common practice? and any easy way to build sorted set off of hash? – ealeon Feb 24 '16 at 17:23
  • @ealeon sorted sets have O1 access to values if you know the full key – Not_a_Golfer Feb 24 '16 at 17:50
  • im reading doc. im not sure if this is possible but i might try using hscan + match – ealeon Feb 24 '16 at 19:25
0

I was able to achieve matching hash keys partially by:

pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
r = redis.StrictRedis(connection_pool=pool)
cmd = "hscan <hashname> 0 match *:atlanta"
print r.execute_command(cmd)
ealeon
  • 12,074
  • 24
  • 92
  • 173