Redis HSTRLEN in Golang (Detailed Guide w/ Code Examples)

Use Case(s)

The HSTRLEN command in Redis is used to get the length of the value of a hash field stored at a key. It is commonly used when you need to know the size of a specific field within a hash, but not the entire hash. This can be particularly useful for storing and retrieving complex data structures like user profiles or sessions where each field might have different lengths.

Code Examples

Here's an example using the go-redis client library:

package main import ( "fmt" "" "context" ) func main() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) ctx := context.Background() err := rdb.HSet(ctx, "userProfile", "username", "myLongUsername").Err() if err != nil { panic(err) } length, err := rdb.HStrLen(ctx, "userProfile", "username").Result() if err != nil { panic(err) } fmt.Printf("Username length: %d\n", length) }

In this code, we first connect to the Redis server running on localhost at port 6379. We then set a hash field 'username' to 'myLongUsername' in the hash at key 'userProfile'. The HSTRLEN command is used to get the length of the value stored at the field 'username'.

Best Practices

  • Always check whether any error occurred during the execution of HSTRLEN command.
  • Be aware that HSTRLEN will return 0 if the key or the field does not exist.

Common Mistakes

  • Incorrect usage of the HSTRLEN command: Do remember that HSTRLEN is for hashes and not for string keys. Using it on non-hash keys will result in an error.
  • Forgetting to handle errors returned from the HSTRLEN or the preceding HSET command can lead to silent failures.


Q: What if the key or field doesn't exist? A: If the key or field does not exist, Redis' HSTRLEN command returns 0.

Q: Does HSTRLEN change the expiration time of the key? A: No, HSTRLEN is a read operation and does not change the expiry time of the key.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.