Skip to content

Ask the HotKV docs

Answers come only from these docs and can be wrong; check the linked pages before you rely on them.

HSETEX

Last updated
HSETEX key [FNX | FXX] [EX seconds | PX milliseconds | EXAT unix-time-seconds | PXAT unix-time-milliseconds | KEEPTTL] FIELDS numfields field value [field value ...]
Group
Hash
Complexity
O(N) where N is the number of fields being set
Arity
-6 (at least 6 words, counting the command name)
Flags
write, fast
Keys
first 1, last 1, step 1
HotKV Cloud
All plans
On-Premise
no license needed

HSETEX writes the given field/value pairs into the hash at key and sets their time to live in the same step. A missing key is created. With FNX or FXX the write is all or nothing: if the condition fails for any field, no field is written.

Without an expiry option, every field written loses any time to live it had. Use KEEPTTL to keep existing field TTLs. An expiry that is already in the past still succeeds, but the fields are removed right away.

Option Effect
FNX Write only if none of the fields exist.
FXX Write only if all of the fields already exist (so the key must exist).
EX seconds Expire the fields after this many seconds.
PX milliseconds Expire the fields after this many milliseconds.
EXAT unix-time-seconds Expire the fields at this Unix time, in seconds.
PXAT unix-time-milliseconds Expire the fields at this Unix time, in milliseconds.
KEEPTTL Keep each field’s current time to live.
FIELDS numfields field value ... The pairs to write. Required, exactly numfields pairs.

FNX and FXX cannot be combined, and only one of EX, PX, EXAT, PXAT and KEEPTTL can be given. The options and the FIELDS block can come in any order after the key.

Case RESP2 RESP3
Fields written Integer 1 Same
Not written because of FNX or FXX Integer 0 Same

Errors:

  • ERR Only one of FXX or FNX arguments can be specified.
  • ERR Only one of EX, PX, EXAT, PXAT or KEEPTTL arguments can be specified.
  • ERR value is not an integer or out of range or ERR invalid expire time, must be >= 0 for a bad time.
  • ERR invalid number of fields, ERR wrong number of arguments (fewer pairs than numfields), ERR FIELDS keyword specified multiple times, ERR missing FIELDS argument, or ERR unknown argument: <arg>.
  • ERR invalid expire time in 'hsetex' command if the time is too far in the future.
  • WRONGTYPE if key holds a value that is not a hash (checked after the arguments).
127.0.0.1:6379> HSETEX session:9 FNX EX 600 FIELDS 2 token "abc" user "42"
(integer) 1
127.0.0.1:6379> HSETEX session:9 FNX EX 600 FIELDS 1 token "xyz"
(integer) 0
127.0.0.1:6379> HSETEX session:9 FXX KEEPTTL FIELDS 1 token "xyz"
(integer) 1
127.0.0.1:6379> HTTL session:9 FIELDS 1 token
1) (integer) 600

Same as Redis 8.0. Redis 7.4 and Valkey 8 do not have this command.

HSET, HGETEX, HEXPIRE, HSETNX, SET