How to Use STRLEN Command in Redis for String Length
Use the
STRLEN command in Redis to get the length of the string stored at a specific key. It returns the number of bytes of the string value or 0 if the key does not exist.Syntax
The STRLEN command syntax is simple:
STRLEN key: Returns the length of the string value stored atkey.
If the key does not exist, it returns 0. If the key holds a non-string type, it returns an error.
redis
STRLEN mykey
Example
This example shows how to set a string value and then get its length using STRLEN:
redis
SET greeting "Hello, Redis!"
STRLEN greetingOutput
13
Common Pitfalls
Common mistakes when using STRLEN include:
- Trying to get length of a key that does not exist returns 0, which might be confused with an empty string.
- Using
STRLENon keys holding non-string types causes an error. - Remember that
STRLENcounts bytes, so multibyte characters count as multiple bytes.
redis
/* Wrong: Using STRLEN on a list key */ LPUSH mylist "item1" STRLEN mylist /* Right: Use STRLEN only on string keys */ SET mystring "abc" STRLEN mystring
Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value
3
Quick Reference
| Command | Description |
|---|---|
| STRLEN key | Returns the length of the string stored at key |
| Returns 0 | If key does not exist |
| Error | If key holds a non-string type |
Key Takeaways
Use STRLEN to get the byte length of a string stored at a Redis key.
STRLEN returns 0 if the key does not exist, not an error.
Do not use STRLEN on keys holding non-string types to avoid errors.
STRLEN counts bytes, so multibyte characters increase length accordingly.