Hash Operations in Code · Redis
Ch 1 · Redis Hashes — card 2 of 4.
Here you see hash commands used from JavaScript on a single user:1 key. Notice how HSET writes several fields at once, while HGET and HMGET read just the fields you ask for and HGETALL returns the lot. Watch HINCRBY add to a counter field, HEXISTS check for a field and HDEL remove one. Every value comes back as a string.
// Set hash fields
await redis.hset("user:1", "name", "Alice", "age", "30", "email", "[email protected]");
// Get single field
const name = await redis.hget("user:1", "name");
console.log(name); // "Alice"
// Get all fields
const user = await redis.hgetall("user:1");
console.log(user); // { name: "Alice", age: "30", email: "[email protected]" }
// Increment a numeric field
await redis.hincrby("user:1", "login_count", 1);
// Check field existence
const hasEmail = await redis.hexists("user:1", "email");
// Delete a field
await redis.hdel("user:1", "email");
// Get specific fields
const partial = await redis.hmget("user:1", "name", "age");
console.log(partial); // ["Alice", "30"]- All hash values are strings
- HGETALL on large hashes is expensive
- Testing if (user) after HGETALL: a missing key returns an empty object {}, which is still truthy, so check Object.keys(user).length instead