Home > Software engineering >  Am I using redigo HDEL correctly?
Am I using redigo HDEL correctly?

Time:10-20

I seem to have the correct usage for using the HDEL command interface, but seem to get 0 records deleted. Am I missing something here?

Here are useful code snippets:

This doesn't work:

keysToDeleteArr []string //this has valid key values from upstream

s.transClient.Do("MULTI")
_, err := s.transClient.Do("HDEL", myhash, keysToDeleteArr)
s.transClient.Do("EXEC")

Gives an output (int64) 0 // # of keys deleted

This does work:

s.transClient.Do("MULTI")
for _, keyToDelete := range keysToDeleteArr {
  _, err := s.transClient.Do("HDEL", myhash, keyToDelete)
}
s.transClient.Do("EXEC")

Gives an output (int64) 1 for each HDEL. From the documentation and from static code analysis on the redigo lib, does seem like slices are acceptable parameters for fields

CodePudding user response:

Construct an []interface{} containing the command arguments. Pass the slice of interface{} to the Do method as a variadic argument:

args := make([]interface{}, 0, len(keysToDeleteArr)   1)
args = append(args, myhash)
for _, v := range keysToDeleteArr {
    args = append(args, v)
}
 _, err := s.transClient.Do("HDEL", args...)

Use Redigo's Args to execute the code above in a single line:

 _, err := s.transClient.Do("HDEL", redis.Args{}.Add(myhash).AddFlat(keysToDeleteArr)...)
  • Related