Skip to main content

HSETEX

Syntax

HSETEX key [NX] [KEEPTTL] seconds field value [field value ...]

Time complexity: O(1) for each field/value pair added, so O(N) to add N field/value pairs when the command is called with multiple field/value pairs.

ACL categories: @read, @hash, @fast

Warning: Experimental! Dragonfly-specific.

Similar to HSET but adds one or more hash fields that expire after specified number of seconds. By default, this command overwrites the values and expirations of specified fields that exist in the hash. If NX option is specified, the field data will not be overwritten. If KEEPTTL option is specified, the TTL for the field will not be overwritten. If key doesn't exist, a new key holding a hash is created.

The expiration time can be accessed with the FIELDTTL command.

Return

Integer reply: The number of fields that were added.

Examples

Cache a user session with a 30-second TTL on every field:

dragonfly> HSETEX session:abc 30 user "alice" role "admin"
(integer) 2
dragonfly> HGETALL session:abc
1) "user"
2) "alice"
3) "role"
4) "admin"
dragonfly> FIELDTTL session:abc user
(integer) 29

Refreshing a field without KEEPTTL resets the TTL:

dragonfly> HSETEX session:abc 60 user "alice-updated"
(integer) 0
dragonfly> FIELDTTL session:abc user
(integer) 60

HSETEX returns the number of NEW fields added, not modified. Above the reply is 0 because user already existed.

Use NX to set a value only if the field does not yet exist (useful for write-once flags):

dragonfly> HSETEX session:abc NX 60 user "bob"
(integer) 0
dragonfly> HGET session:abc user
"alice-updated"
dragonfly> HSETEX session:abc NX 60 ip "10.0.0.1"
(integer) 1
dragonfly> HGET session:abc ip
"10.0.0.1"

Use KEEPTTL to update a value without changing its existing expiry — useful when refreshing data but keeping the original session deadline:

dragonfly> FIELDTTL session:abc ip
(integer) 58
dragonfly> HSETEX session:abc KEEPTTL 9999 ip "10.0.0.2"
(integer) 0
dragonfly> FIELDTTL session:abc ip
(integer) 56
dragonfly> HGET session:abc ip
"10.0.0.2"

Note: the 9999 argument is required by the syntax but ignored when KEEPTTL is set.