Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Redis Hsetnx Command

Redis Hsetnx Command

Redis Hash

The Redis Hsetnx command is used to set the value of a field in the hash only if the field does not exist.

If the hash does not exist, a new hash is created and the HSET operation is performed.

If the field already exists in the hash, the operation has no effect.

If key does not exist, a new hash is created and the HSETNX command is executed.

Syntax

The basic syntax of the redis Hsetnx command is as follows:



redis 127.0.0.1:6379> HSETNX KEY_NAME FIELD VALUE

Available Version

= 2.0.0

Return Value

Returns 1 on success. Returns 0 if the given field already exists and no operation was performed.

Example



redis 127.0.0.1:6379> HSETNX myhash field1 "foo"

(integer) 1

redis 127.0.0.1:6379> HSETNX myhash field1 "bar"

(integer) 0

redis 127.0.0.1:6379> HGET myhash field1

"foo"



redis 127.0.0.1:6379> HSETNX nosql key-value-store redis

(integer) 1



redis 127.0.0.1:6379> HSETNX nosql key-value-store redis       # 操作无效, key-value-store 已存在

(integer) 0

Redis Hash