Aaron Yodaiken
Aaron Yodaiken

Reputation: 19551

Atomic set only if not already set

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.

Upvotes: 8

Views: 5882

Answers (1)

Sripathi Krishnan
Sripathi Krishnan

Reputation: 31528

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.

Upvotes: 10

Related Questions