Skip to main content

Command Palette

Search for a command to run...

Most Used Redis Operations (with Node.js examples)

Updated
4 min read
K
Backend-focused web developer and engineering student.

Using the ioredis library (npm install ioredis):

import Redis from "ioredis";
const redis = new Redis(); // connects to localhost:6379

String Operations

// SET & GET
await redis.set("name", "Alice");
const name = await redis.get("name"); // "Alice"

// SET with expiry (TTL in seconds)
await redis.set("session", "abc123", "EX", 3600); // expires in 1 hour

// SET only if not exists
await redis.setnx("lock", "1");

// Increment / Decrement
await redis.set("counter", 0);
await redis.incr("counter");        // 1
await redis.incrby("counter", 5);   // 6
await redis.decr("counter");        // 5

// Delete a key
await redis.del("name");

// Check if key exists
const exists = await redis.exists("name"); // 0 or 1

// Get TTL
const ttl = await redis.ttl("session"); // seconds remaining

// Set TTL on existing key
await redis.expire("name", 60);

Hash Operations (like objects/maps)

// Set single field
await redis.hset("user:1", "name", "Alice");

// Set multiple fields
await redis.hset("user:1", { name: "Alice", age: "30", city: "NYC" });

// Get single field
const name = await redis.hget("user:1", "name"); // "Alice"

// Get all fields
const user = await redis.hgetall("user:1"); // { name: "Alice", age: "30", ... }

// Delete a field
await redis.hdel("user:1", "city");

// Check if field exists
const exists = await redis.hexists("user:1", "name"); // 0 or 1

List Operations (ordered, allows duplicates)

// Push to left / right
await redis.lpush("tasks", "task1");
await redis.rpush("tasks", "task2", "task3");

// Pop from left / right
const first = await redis.lpop("tasks"); // "task1"
const last  = await redis.rpop("tasks"); // "task3"

// Get range (0 = first, -1 = last)
const all = await redis.lrange("tasks", 0, -1);

// Length
const len = await redis.llen("tasks");

Set Operations (unique values, unordered)

// Add members
await redis.sadd("tags", "nodejs", "redis", "backend");

// Remove member
await redis.srem("tags", "backend");

// Get all members
const tags = await redis.smembers("tags"); // ["nodejs", "redis"]

// Check membership
const isMember = await redis.sismember("tags", "redis"); // 1

// Set size
const size = await redis.scard("tags");

// Intersection / Union / Difference
await redis.sadd("setA", "a", "b", "c");
await redis.sadd("setB", "b", "c", "d");
const inter = await redis.sinter("setA", "setB"); // ["b", "c"]
const union = await redis.sunion("setA", "setB"); // ["a","b","c","d"]
const diff  = await redis.sdiff("setA", "setB");  // ["a"]

Sorted Set Operations (unique values + score)

// Add with score
await redis.zadd("leaderboard", 100, "Alice");
await redis.zadd("leaderboard", 200, "Bob");
await redis.zadd("leaderboard", 150, "Carol");

// Get rank (0-indexed, low to high)
const rank = await redis.zrank("leaderboard", "Alice"); // 0

// Get range by rank (low to high)
const bottom = await redis.zrange("leaderboard", 0, -1); // ["Alice","Carol","Bob"]

// Get range with scores
const withScores = await redis.zrange("leaderboard", 0, -1, "WITHSCORES");

// Get range high to low
const top = await redis.zrevrange("leaderboard", 0, 2);

// Get score of a member
const score = await redis.zscore("leaderboard", "Bob"); // "200"

// Remove member
await redis.zrem("leaderboard", "Alice");

Pub/Sub

const sub = new Redis();
const pub = new Redis();

// Subscribe
sub.subscribe("news", (err, count) => {
  console.log(`Subscribed to ${count} channels`);
});

sub.on("message", (channel, message) => {
  console.log(`[\({channel}]: \){message}`);
});

// Publish
await pub.publish("news", "Hello World!");

Atomic Multi/Exec (Transaction)

const results = await redis
  .multi()
  .set("a", 1)
  .incr("a")
  .get("a")
  .exec();
// results: [["OK"], [2], ["2"]]

Scan (safe alternative to KEYS * in production)

// Iterate all keys matching a pattern
let cursor = "0";
do {
  const [nextCursor, keys] = await redis.scan(cursor, "MATCH", "user:*", "COUNT", 100);
  cursor = nextCursor;
  console.log(keys);
} while (cursor !== "0");

Category Key Commands
String set, get, del, exists, expire, ttl, incr, decr
Hash hset, hget, hgetall, hdel, hexists
List lpush, rpush, lpop, rpop, lrange, llen
Set sadd, srem, smembers, sismember, sinter, sunion
Sorted Set zadd, zrange, zrevrange, zrank, zscore, zrem
Pub/Sub subscribe, publish
Transaction multi, exec
Utility scan, keys, type, rename, persist

More from this blog