1

I want to store key-value pairs(T1,T2) in Redis. Both key and value are unique. I want to be able to query on both key and value, i.e. HGET(Key) should return corresponding Value and HGET(Value) should return corresponding Key.

A trivial approach would be to create 2 Hashes in Redis (T1,T2) and (T2,T1) and then query on appropriate Hash. Problem with this approach is that insertion, update or deletion of pairs would need updates in both Hashes.

Is there a better way to serve my requirement...

Vijay Kansal
  • 809
  • 12
  • 26

1 Answers1

1

If one of T1, T2 has an integer type you could use a combo like:

1->foo
2->bar

ZADD myset 1 foo
ZADD myset 2 bar

ZSCORE myset foo //returns 1.0 in O(n)
ZSCORE myset bar //return 2.0 in O(n)

ZRANGEBYSCORE myset 1 1 //returns "foo" in O(log(N)+M)

source

If this is not the case then it makes sense to maintain 2 separate hashes, preferably within a Lua script

Ion Cojocaru
  • 2,583
  • 15
  • 16
  • Thanks Ion for your response. Both Key and Value are strings in my current requirement, and hence I cannot use Sorted Sets here, but the solution you suggested is very informative and I'll hopefully use it in some other similar requirement :) – Vijay Kansal Sep 24 '14 at 07:52