8

Is there any way to do an atomic set only if not already set in Redis?

Specifically, I'm creating a user like "myapp:user:user_email" and want Redis to give me back an error if "user_email" is already taken, instead of silently replacing the old value. Something like declare, not replace.

Aaron Yodaiken
  • 19,163
  • 32
  • 103
  • 184

1 Answers1

9

See SETNX

Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. SETNX is short for "SET if N ot e X ists".

You can check the return value. If it is 0, the key was not set, implying it already existed.

Sripathi Krishnan
  • 30,948
  • 4
  • 76
  • 83