I have a collection where each Foo maps to exactly one Bar, and each Bar maps to exactly one Foo. I need to be able to look up the corresponding Foo given a Bar, and look up the corresponding Bar given a Foo.
In order to do this, at the moment, I have created two hashmaps, and each time I do an insert, I perform 2 HSET
s, one on each hashmap:
HSET fooToBar foo1 bar1
HSET barToFoo bar1 foo1
After this, lookups are very easy in either direction:
//Look up bar given a foo
HGET fooToBar foo1
//Look up foo given a bar
HGET barToFoo bar1
However, I am not completely satisfied with this solution. In the application I am using this in, space constraints are going to be more important than speed constraints, and this I would prefer to have just one data structure instead of two, even if it means a more expensive look up (within reason).
Is there a better way to implement a bidirectional hash map in Redis?
To create a hash, run the hset command. This command accepts the name of the hash key, the field string, and the corresponding value string as arguments: hset poet:Verlaine nationality French.
Redis doesn't support storing hash inside hash. But there is REDIS as a JSON store that can store JSON in REDIS, It allows storing, updating and fetching JSON values from Redis keys.
You can store your data in a sorted set instead of a hash, the foos are strings so those will be your values, and bars are integers so those will be your scores.
Adding a new foo.
ZADD myzset bar foo
Getting bar using foo.
ZSCORE myzset foo
Getting foo using bar
ZRANGEBYSCORE myzset bar bar
Keep in mind hgets are O(1). zscore is O(1) as well but zrangebyscore is O(log(N)+M) where N is the member count in the sorted set and M is the number of elements returned. Not sure if this will save you space but worth a shot I think.
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