How to Get Value in Redis: Simple Guide with Examples
To get a value in Redis, use the
GET command followed by the key name. For example, GET mykey returns the value stored at mykey or (nil) if the key does not exist.Syntax
The basic syntax to get a value from Redis is:
GET key: Retrieves the value stored at the specifiedkey.- If the
keyexists, Redis returns its value as a string. - If the
keydoes not exist, Redis returns(nil).
redis
GET key
Example
This example shows how to set a key and then get its value using Redis commands.
redis
SET favorite_color blue GET favorite_color GET missing_key
Output
"OK"
"blue"
(nil)
Common Pitfalls
Common mistakes when getting values in Redis include:
- Trying to get a value from a key that does not exist, which returns
(nil). - Confusing data types:
GETonly works with string keys, not hashes or lists. - Not checking the response for
(nil)which means the key is missing.
redis
GET myhash
# Correct way to get a field from a hash:
HGET myhash field1Output
(error) WRONGTYPE Operation against a key holding the wrong kind of value
"value1"
Quick Reference
| Command | Description | Example |
|---|---|---|
| GET key | Get the string value of a key | GET username |
| SET key value | Set the string value of a key | SET username alice |
| HGET key field | Get the value of a hash field | HGET user:1 name |
| (nil) | Returned when key does not exist | GET missing_key |
Key Takeaways
Use the GET command followed by the key name to retrieve a value in Redis.
GET returns the string value or (nil) if the key does not exist.
GET only works with string keys; use HGET for hash fields.
Always check for (nil) to handle missing keys gracefully.