2
votes

I would like to reset the value of a REDIS counter to 0 in a Rails 4 app.

I use hincrby to increment counters

 $redis.hincrby("user:likes", "key", 1)

I can't delete the key with hdel http://redis.io/commands/hdel because I need to get the key often.

GETSET is atomic and could do the job http://redis.io/commands/getset, as in the example

 GETSET mycounter "0"

But since I use hashes I need to use HSET http://redis.io/commands/hset

$redis.hset("user:likes", "key", "0")

It's not specified if hset is atomic, anyone used hset to reset redis counters to 0? If it's not a good option to reset a counter to 0, any idea how to do it?

1
Not sure I understand. If you need to set it to zero, set it to zero. Or are you saying you really need GETSET functionality, but for the hash?Philip Hallstrom
It's specified in the docs that GETSET is atomic but it's not specified for HSET, so is HSET atomic?stefano_cdn
I don't know, but GETSET is two operations. HSET is one, so I imagine would be atomic, no?Philip Hallstrom

1 Answers

2
votes

It is atomic, so if you run $redis.hset("user:likes", "key", "0"), it doesn't affect other fields inside the "user:likes" hash besides the field: "key"