Core Redis Data Types and Common Operations
🎯 Introduction
By the end of this article, you will be able to choose Redis types for complete records, object fields, lists, unique members, and rankings, and perform common operations on them.
This article uses Node.js 22.9.0, redis 5.9.0, and Redis 7.4.2. Reuse redis.mjs from the introduction, and add the following blocks to types.mjs in order. Start by connecting and clearing the exercise keys:
import { redis } from './redis.mjs';
await redis.connect();
await redis.del([
'course:types:number', 'course:types:json',
'course:types:hash', 'course:types:list', 'course:types:set',
'course:types:other', 'course:types:rank',
]);
Delete only these practice keys so old data does not affect the output.
🧱 String: Text, Numbers, and JSON
String is Redis's string type: each key holds one complete value. A read retrieves the entire value; writing to the same key replaces it. Numbers and JSON can be represented as strings, but Redis does not automatically turn them into JavaScript numbers or objects.
Use cases: text, a numeric value, or a query result that you read as a whole. The introduction covered plain text; here we will work with numbers and JSON.
Numbers can be stored as text:
await redis.set('course:types:number', '10');
console.log(await redis.get('course:types:number'));
The result is the string "10", not a JavaScript number. For counters, use the atomic increment commands covered later instead of reading and overwriting the value yourself.
Serialize objects as JSON before storing them:
const user = { id: '42', name: 'Lin' };
await redis.set('course:types:json', JSON.stringify(user));
const raw = await redis.get('course:types:json');
console.log(raw === null ? null : JSON.parse(raw));
This prints the user object. The example assumes the current program wrote the contents; application caches also need to handle invalid JSON. A regular String does not support updating individual JSON fields, so changing the name requires replacing the entire text.
🛠 Hash: Store and Update Object Fields
A Hash is a collection of field-value pairs under one key. Each named field can be read and written independently. Updating one field does not overwrite the others.
Use cases: relatively flat records whose fields need independent updates, such as a user's name and city. Write the fields, then read just the city:
await redis.hSet('course:types:hash', { name: 'Lin', city: 'Hangzhou' });
console.log(await redis.hGet('course:types:hash', 'city'));
The output is Hangzhou. hSet writes fields, while hGet reads only the specified field.
Update only the city, then read all fields:
await redis.hSet('course:types:hash', 'city', 'Suzhou');
console.log(await redis.hGetAll('course:types:hash'));
The result contains name: 'Lin' and city: 'Suzhou'; the name is unchanged. Field values are still strings. Nested objects do not automatically become nested structures.
🧰 List: Lists, Queues, and Stacks
A List is an ordered list of strings that allows duplicates. You can push and pop elements at either end, or read a range by position. Popping removes elements; reading leaves them in place.
Use cases: ordered records, simple queues, and stacks. A queue processes items first in, first out; a stack processes them last in, first out.
Push on the right and pop from the left to observe queue order:
await redis.rPush('course:types:list', ['A', 'B', 'C']);
console.log(await redis.lPop('course:types:list'));
The output is A. Next, push on the right and pop from the right to observe stack order:
await redis.rPush('course:types:list', 'D');
console.log(await redis.rPop('course:types:list'));
console.log(await redis.lRange('course:types:list', 0, 1));
The outputs are D and ['B', 'C']. The end index in lRange is inclusive, and reading does not remove elements.
Popping an element directly provides no processing acknowledgment. If a process exits after receiving an item, the unprocessed task may be lost. A simple List alone is therefore unsuitable for task processing that requires retries after failure.
💡 Set: Uniqueness, Membership, and Set Operations
A Set contains unique members and does not guarantee return order. Adding the same member again does not create a duplicate. Redis can also test membership and compare intersections and differences between sets.
Use cases: deduplicating tags, checking membership in follow relationships, and finding members shared by two groups. Use tags to test deduplication and membership:
console.log(await redis.sAdd('course:types:set', ['js', 'vue', 'js']));
console.log(await redis.sIsMember('course:types:set', 'js'));
The outputs are 2 and 1: two members were added, and js exists. A membership check returns 0 when the member is absent.
Find the tags shared by both groups:
await redis.sAdd('course:types:other', ['js', 'css']);
console.log(await redis.sInter(['course:types:set', 'course:types:other']));
The output is ['js']. sUnion returns the union, while sDiff returns members of the first set absent from subsequent sets. With large datasets, both set operations and their returned results consume resources.
✨ Sorted Set: Ordering, Scores, and Leaderboards
A Sorted Set associates each unique member with a numeric score. Redis orders members by score and supports queries over rank or score ranges. Members are unique, but different members can share a score.
Use cases: points leaderboards, or records whose scores represent timestamps for time-range queries. Use points to observe ordering:
await redis.zAdd('course:types:rank', [
{ value: 'Lin', score: 80 },
{ value: 'Mei', score: 95 },
{ value: 'Kai', score: 70 },
]);
value is the member; score determines its order. Adding an existing member updates its score. Read the top two members:
console.log(await redis.zRangeWithScores('course:types:rank', 0, 1, { REV: true }));
The result lists Mei with 95 points, then Lin with 80. 0, 1 selects the first two positions, and REV: true orders scores from highest to lowest. Ties use bytewise lexicographical ordering of members; other tie-breaking rules require a separate design.
⚖️ Choosing Among the Five Types
| Requirement | Type | Reason |
|---|---|---|
| A complete API JSON response | String | Convenient to read and replace as a whole |
| Update individual object fields | Hash | Other fields do not need to be overwritten |
| Preserve order and allow duplicates | List | Push and pop at either end |
| Uniqueness, membership, and intersections | Set | Manage a collection by member |
| Rankings by points | Sorted Set | Store members with their scores |
A key has only one type at a time. Calling regular get on a Hash raises WRONGTYPE; choose commands that match the stored structure. See Redis data types for their uses.
Finally, close the connection:
await redis.close();
Run the complete script and observe the outputs in the order above:
node types.mjs
❓ Questions and Answers
Q1: How does JSON in a String differ from a Hash?
JSON is one block of text; Hash fields can be read and written independently. Choose based on how you update the data, rather than whether it is a JavaScript object.
Q2: Does a List automatically remove duplicates?
No. Use a Set for unique members, or consider a Sorted Set if they also need ordering.
Q3: Can an endpoint return an entire large collection?
Limit the result size. Reading, transferring, and converting many elements to JSON all consume resources. Prefer range queries or batches.
🧪 Exercise
Update Kai's leaderboard score to 100, then read the top two members. Delete one Hash field and inspect the remaining fields.
// Write your code here
// Hint: zAdd, zRangeWithScores, hDel, hGetAll
🎉 You now know how to choose among the common Redis data types!
