redis-om-python icon indicating copy to clipboard operation
redis-om-python copied to clipboard

How to achieve "HSetNX" functionality?

Open oren-twigo opened this issue 3 years ago • 2 comments

What is the recommended way to mimic HSETNX command? (https://redis.io/commands/hsetnx/) The question refers to both Json and Hash models.

my use case: I have a key with "created_timestamp" field. I would like to set it only upon the first set of the key, and avoid updating it upon updating the other fields of that key.

currently the only solution I can think of is checking if key exists before "save()" command, and set the field accordingly. This will require to check a key before each save command.

Any better solution?

oren-twigo avatar May 14 '22 13:05 oren-twigo

I can imagine this could work for hash models by having some sort of flag optional parameter to save that, when set, uses the HSETNX command instead of HSET here: https://github.com/redis/redis-om-python/blob/878490abb774102c0e119d1288173197fe85e552/aredis_om/model/model.py#L1312 - might have to then re-read the hash from Redis and return that, in case what was passed into save isn't what's in Redis as a result of this operation. If you wanted to toggle the HSETNX behaviour on a per field basis that might require more thought.

For JSON I think this would have to be done as some sort of transaction.

simonprickett avatar May 18 '22 10:05 simonprickett