Redis Hsetnx Command

Redis Hash (Hash)

The Redis Hsetnx command is used to assign a value to a field that does not exist in the hash table.

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

If the field already exists in the hash table, the operation is invalid.

If the key does not exist, a new hash table 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 Versions

>= 2.0.0

Return Value

On success, 1 is returned. If the given field already exists and no operation is performed, 0 is returned.

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 (Hash)

Other Extensions