0

I am storing some values in redis like for key: 1 the value will be

{"counter":1,"counter1":2}

Now I need to reset value of counter while the counter1 should be remaining same.

To increase counter I am use the command SETEX mykey 60 redis .

But it will also reset the value of counter1. So is there any way I can reset one value for a single key.

Let me know if I need to add some more info.

Ersoy
  • 8,816
  • 6
  • 34
  • 48
Soham
  • 4,397
  • 11
  • 43
  • 71

1 Answers1

2

Instead of string you may use hash, then it will be easy. you can increment by some other value, delete counter etc etc. Each key in your json will be hash field.

127.0.0.1:6379> hset mykey counter 1 counter1 2
(integer) 2
127.0.0.1:6379> hgetall mykey
1) "counter"
2) "1"
3) "counter1"
4) "2"
127.0.0.1:6379> hset mykey counter 25
(integer) 0
127.0.0.1:6379> hgetall mykey
1) "counter"
2) "25"
3) "counter1"
4) "2"
127.0.0.1:6379> HINCRBY mykey counter 15
(integer) 40
127.0.0.1:6379> hgetall mykey
1) "counter"
2) "40"
3) "counter1"
4) "2"
127.0.0.1:6379>
Ersoy
  • 8,816
  • 6
  • 34
  • 48
  • So if I use SETEX mykey 10 then both counter will be reset right? If I am right then how can I avoid that ? I want to reset only counter value in every 1 minute not the counter1 value. – Soham Jun 15 '20 at 06:02
  • @Soham you won't use setex you will use hset - the solution i provided shows how to reset a single field while keeping other the same. – Ersoy Jun 15 '20 at 08:31
  • Thanks for your answer.But I need to reset the value after say 1 minute.So can I give some expiry time in seconds using hset. – Soham Jun 15 '20 at 13:49
  • @Soham it is not possible with hash (you can't partially expire a field) - you can completely expire hash. There are some misused terms i think in your question. But i offered this solution as "reset" means "reset"ting/setting it to zero the value not "expire"ing completely. – Ersoy Jun 15 '20 at 14:08
  • @Soham you may check here https://stackoverflow.com/questions/16545321/how-to-expire-the-hset-child-key-in-redis – Ersoy Jun 15 '20 at 14:13
  • 1
    Sorry if my question isn't clear at all. Your answer is fine according to my question so I am accepting your answer. – Soham Jun 15 '20 at 16:00