0
0
Redisquery~5 mins

Hash vs string for objects in Redis

Choose your learning style9 modes available
Introduction
Hashes and strings are two ways to store data in Redis. Choosing between them helps you organize and access your data easily.
When you want to store multiple related pieces of information about one item, like a user's name and age.
When you need to update or read just one part of an object without changing the whole thing.
When you want to save memory by grouping related fields together instead of using many separate keys.
When you want simple key-value pairs without structure, use strings.
When you want to store objects with fields, use hashes.
Syntax
Redis
For string:
SET key value
GET key

For hash:
HSET key field value [field value ...]
HGET key field
HGETALL key
Strings store one value per key, like a label on a box.
Hashes store multiple fields under one key, like a box with compartments.
Examples
Stores the whole user name as a simple string.
Redis
SET user:1 "John Doe"
Stores user details as fields inside a hash.
Redis
HSET user:1 name "John Doe" age 30
Gets just the name field from the user hash.
Redis
HGET user:1 name
Gets the whole string value stored at user:1.
Redis
GET user:1
Sample Program
This example shows storing multiple fields in a hash and retrieving them all, then trying to get a string key that does not exist.
Redis
HSET user:100 name "Alice" age 28 city "Paris"
HGETALL user:100
GET user:100
OutputSuccess
Important Notes
Hashes are efficient for storing objects with multiple fields.
Strings are simpler but less flexible for structured data.
Use HGETALL carefully on large hashes as it returns all fields.
Summary
Strings store single values per key, good for simple data.
Hashes store multiple fields under one key, good for objects.
Choose based on how you want to organize and access your data.