17

I want to store multiple keys with a single value using jedis (Redis cache) with Java.

I have three keys like user_1, driver_10, admin_5 and value = this is user, and I want to get value by using any one key among those three.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user3864113
  • 237
  • 1
  • 2
  • 8
  • Could you clarify what exacly is your key? Is it `[user_10,driver_5]` including brackets? Which [redis java client](https://redis.io/clients#java) are you using? jedis, jredis? (don't know any "jdis") – Hugues M. Jun 02 '17 at 19:03
  • I want to add multiple key which is pointing single value suppose i have three keys like user_1,driver_10,admin_5 and value = "this is user" and i want to get value by using any one key among three – user3864113 Jun 06 '17 at 12:23

2 Answers2

23

Having multiple keys point to same value is not supported in Redis for now, see issue #2668.

You would need a workaround.

Some ideas below, possibly obvious or stupid :)


Maybe have an intermediate key:
- user_10id_123
- driver_5id_123
- id_123data_that_you_dont_want_to_duplicate

You could implement that logic in your client code, or in custom Lua scripts on server, and have your client code use those scripts (but I don't know enough about that to provide details).

If you implement the indirection logic on client side, and if accesses are unbalanced, for example you would access data via user key 99% of the time, and via driver key 1% of the time, it might be worth avoiding 2 client-server round trips for the 99% case. For this you can encode redirections. For example, if first character is # then the rest is the data. If first character is @ then the rest is the actual key.

  • user_10#data_that_you_dont_want_to_duplicate
  • driver_5@user_10
Hugues M.
  • 19,846
  • 6
  • 37
  • 65
  • 1
    I want to add multiple key which is pointing single value suppose i have three keys like user_1,driver_10,admin_5 and value = "this is user" and i want to get value by using any one key among three – user3864113 Jun 06 '17 at 12:26
  • 2
    OK then I think I understood correctly, and the first sentence of my answer is relevant: that is not supported currently, so you can go comment on the linked github issue, or consider workarounds. – Hugues M. Jun 06 '17 at 12:28
  • Your workaround makes absolute sense. It's super brilliant not stupid – Peter Moses Feb 11 '22 at 06:52
  • Suppose I wanted to invalidate `#data_that_you_dont_want_to_duplicate`. I could invalidate `user_10`, but then how does the `driver_5 -> @user_10` K-V get cleaned up in redis? – OscarVanL Jul 24 '23 at 21:15
3

Here is a Lua script that can save on trafic, and pull the data in one call:

eval "return redis.call('get',redis.call('get',KEYS[1]))" 1 user-10

The above will return the request data.

Erdogan Kurtur
  • 3,630
  • 21
  • 39
J. Doe
  • 31
  • 2