Atomic set only if not already set
Asked Answered
S

1

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.

Seventh answered 23/4, 2013 at 0:47 Comment(0)
P
10

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.

Preview answered 23/4, 2013 at 3:33 Comment(1)
Hi, you answered the question but wondered if there is a similar solution for (H)MSETs?Seventh

© 2022 - 2024 — McMap. All rights reserved.