upstash-redis-js

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Upstash Redis SDK - Complete Skills Guide

Upstash Redis SDK 完整技能指南

This directory contains comprehensive guides for using the
@upstash/redis
SDK. These skill files are designed to help developers and AI assistants understand and use the SDK effectively.
本目录包含使用
@upstash/redis
SDK 的全面指南。这些技能文件旨在帮助开发者和 AI 助手高效理解并使用该 SDK。

Installation

安装

bash
npm install @upstash/redis
bash
npm install @upstash/redis

Quick Start

快速开始

Basic Initialization

基础初始化

typescript
import { Redis } from "@upstash/redis";

// Initialize with explicit credentials
const redis = new Redis({
  url: "UPSTASH_REDIS_REST_URL",
  token: "UPSTASH_REDIS_REST_TOKEN",
});

// Or initialize from environment variables
const redis = Redis.fromEnv();
typescript
import { Redis } from "@upstash/redis";

// Initialize with explicit credentials
const redis = new Redis({
  url: "UPSTASH_REDIS_REST_URL",
  token: "UPSTASH_REDIS_REST_TOKEN",
});

// Or initialize from environment variables
const redis = Redis.fromEnv();

Environment Variables

环境变量

Set these in your
.env
file:
bash
UPSTASH_REDIS_REST_URL=https://your-redis.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-token-here
.env
文件中设置以下变量:
bash
UPSTASH_REDIS_REST_URL=https://your-redis.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-token-here

Skill Files Overview

技能文件概览

Data Structures (skills/data-structures/)

数据结构 (skills/data-structures/)

Redis data types with auto-serialization examples:
  • strings.md - GET, SET, INCR, DECR, APPEND with automatic type handling
  • hashes.md - HSET, HGET, HMGET with object serialization
  • lists.md - LPUSH, RPUSH, LRANGE with array handling
  • sets.md - SADD, SMEMBERS, set operations
  • sorted-sets.md - ZADD, ZRANGE, ZRANK, leaderboard patterns
  • json.md - JSON.SET, JSON.GET, JSONPath queries for nested objects
  • streams.md - XADD, XREAD, XGROUP, consumer groups
带自动序列化示例的 Redis 数据类型:
  • strings.md - 带自动类型处理的 GET、SET、INCR、DECR、APPEND 操作
  • hashes.md - 带对象序列化的 HSET、HGET、HMGET 操作
  • lists.md - 带数组处理的 LPUSH、RPUSH、LRANGE 操作
  • sets.md - SADD、SMEMBERS 及集合操作
  • sorted-sets.md - ZADD、ZRANGE、ZRANK 及排行榜模式
  • json.md - JSON.SET、JSON.GET 及针对嵌套对象的 JSONPath 查询
  • streams.md - XADD、XREAD、XGROUP 及消费者组

Advanced Features (skills/advanced-features/)

高级功能 (skills/advanced-features/)

Complex operations and optimizations:
  • auto-pipeline.md - Automatic request batching, performance optimization
  • pipeline-and-transactions.md - Manual pipelines, MULTI/EXEC, WATCH for atomic operations
  • scripting.md - Lua scripts, EVAL, EVALSHA for server-side logic
复杂操作与优化:
  • auto-pipeline.md - 自动请求批处理与性能优化
  • pipeline-and-transactions.md - 手动管道、MULTI/EXEC、WATCH 原子操作
  • scripting.md - Lua 脚本、EVAL、EVALSHA 服务端逻辑

Patterns (skills/patterns/)

模式 (skills/patterns/)

Common use cases and architectural patterns:
  • caching.md - Cache-aside, write-through, TTL strategies
  • rate-limiting.md - Integration with @upstash/ratelimit package
  • session-management.md - Session storage and user state management
  • distributed-locks.md - Lock implementations, deadlock prevention
  • leaderboard.md - Sorted set leaderboards, real-time rankings
常见用例与架构模式:
  • caching.md - 缓存旁路、写穿透、TTL 策略
  • rate-limiting.md - 与 @upstash/ratelimit 包集成
  • session-management.md - 会话存储与用户状态管理
  • distributed-locks.md - 锁实现与死锁预防
  • leaderboard.md - 有序集合排行榜与实时排名

Performance (skills/performance/)

性能优化 (skills/performance/)

Optimization techniques and best practices:
  • batching-operations.md - MGET, MSET, batch operations
  • pipeline-optimization.md - When to use pipelines, performance tips
  • ttl-expiration.md - Key expiration strategies, memory management
  • data-serialization.md - Deep dive into auto serialization, custom serializers, edge cases
  • error-handling.md - Error types, retry strategies, timeout handling, debugging tips
  • redis-replicas.md - Global database setup, read replicas, read-your-writes consistency
优化技巧与最佳实践:
  • batching-operations.md - MGET、MSET 及批量操作
  • pipeline-optimization.md - 管道使用场景与性能技巧
  • ttl-expiration.md - 键过期策略与内存管理
  • data-serialization.md - 自动序列化深入解析、自定义序列化器与边缘案例
  • error-handling.md - 错误类型、重试策略、超时处理与调试技巧
  • redis-replicas.md - 全局数据库设置、只读副本与读写一致性

Search (skills/search/)

搜索功能 (skills/search/)

Full-text search, filtering, and aggregation extension for Redis:
  • overview.md - Schema definition, field types, pitfalls, package overview
  • commands/querying.md - Query and count with filters, pagination, sorting, highlighting
  • commands/aggregating.md - Metric aggregations ($avg, $sum, $stats), bucket aggregations ($terms, $range, $histogram, $facet)
  • commands/index-management.md - Create, describe, drop indexes, waitIndexing
  • commands/aliases.md - Index aliases for zero-downtime reindexing
  • adapters.md - Using search with node-redis and ioredis via @upstash/search-redis and @upstash/search-ioredis
Redis 的全文搜索、过滤与聚合扩展:
  • overview.md - Schema 定义、字段类型、常见陷阱与包概览
  • commands/querying.md - 带筛选器的查询与计数、分页、排序、高亮显示
  • commands/aggregating.md - 指标聚合($avg、$sum、$stats)、桶聚合($terms、$range、$histogram、$facet)
  • commands/index-management.md - 创建、描述、删除索引与 waitIndexing
  • commands/aliases.md - 用于零停机重新索引的索引别名
  • adapters.md - 通过 @upstash/search-redis 和 @upstash/search-ioredis 适配 node-redis 与 ioredis 使用搜索功能

Migrations (skills/migrations/)

迁移指南 (skills/migrations/)

Migration guides from other libraries:
  • from-ioredis.md - Migration from ioredis, key differences, serialization changes
  • from-redis-node.md - Migration from node-redis, API differences
从其他库迁移的指南:
  • from-ioredis.md - 从 ioredis 迁移的关键差异与序列化变更
  • from-redis-node.md - 从 node-redis 迁移的 API 差异

Common Mistakes (Especially for LLMs)

常见错误(尤其针对大语言模型)

❌ Mistake 1: Treating Everything as Strings

❌ 错误1:将所有内容视为字符串

typescript
// ❌ WRONG - Don't do this with @upstash/redis
await redis.set("count", "42"); // Stored as string "42"
const count = await redis.get("count");
const incremented = parseInt(count) + 1; // Manual parsing needed

// ✅ CORRECT - Let the SDK handle it
await redis.set("count", 42); // Stored as number
const count = await redis.get("count");
const incremented = count + 1; // Just use it
typescript
// ❌ WRONG - Don't do this with @upstash/redis
await redis.set("count", "42"); // Stored as string "42"
const count = await redis.get("count");
const incremented = parseInt(count) + 1; // Manual parsing needed

// ✅ CORRECT - Let the SDK handle it
await redis.set("count", 42); // Stored as number
const count = await redis.get("count");
const incremented = count + 1; // Just use it

❌ Mistake 2: Manual JSON Serialization

❌ 错误2:手动 JSON 序列化

typescript
// ❌ WRONG - Unnecessary with @upstash/redis
await redis.set("user", JSON.stringify({ name: "Alice" }));
const user = JSON.parse(await redis.get("user"));

// ✅ CORRECT - Automatic handling
await redis.set("user", { name: "Alice" });
const user = await redis.get("user");
typescript
// ❌ WRONG - Unnecessary with @upstash/redis
await redis.set("user", JSON.stringify({ name: "Alice" }));
const user = JSON.parse(await redis.get("user"));

// ✅ CORRECT - Automatic handling
await redis.set("user", { name: "Alice" });
const user = await redis.get("user");

Quick Command Reference

快速命令参考

typescript
// Strings
await redis.set("key", "value");
await redis.get("key");
await redis.incr("counter");
await redis.decr("counter");

// Hashes
await redis.hset("user:1", { name: "Alice", age: 30 });
await redis.hget("user:1", "name");
await redis.hgetall("user:1");

// Lists
await redis.lpush("tasks", "task1", "task2");
await redis.rpush("tasks", "task3");
await redis.lrange("tasks", 0, -1);

// Sets
await redis.sadd("tags", "javascript", "redis");
await redis.smembers("tags");

// Sorted Sets
await redis.zadd("leaderboard", { score: 100, member: "player1" });
await redis.zrange("leaderboard", 0, -1);

// JSON
await redis.json.set("user:1", "$", { name: "Alice", address: { city: "NYC" } });
await redis.json.get("user:1");

// Expiration
await redis.setex("session", 3600, { userId: "123" });
await redis.expire("key", 60);
await redis.ttl("key");
typescript
// Strings
await redis.set("key", "value");
await redis.get("key");
await redis.incr("counter");
await redis.decr("counter");

// Hashes
await redis.hset("user:1", { name: "Alice", age: 30 });
await redis.hget("user:1", "name");
await redis.hgetall("user:1");

// Lists
await redis.lpush("tasks", "task1", "task2");
await redis.rpush("tasks", "task3");
await redis.lrange("tasks", 0, -1);

// Sets
await redis.sadd("tags", "javascript", "redis");
await redis.smembers("tags");

// Sorted Sets
await redis.zadd("leaderboard", { score: 100, member: "player1" });
await redis.zrange("leaderboard", 0, -1);

// JSON
await redis.json.set("user:1", "$", { name: "Alice", address: { city: "NYC" } });
await redis.json.get("user:1");

// Expiration
await redis.setex("session", 3600, { userId: "123" });
await redis.expire("key", 60);
await redis.ttl("key");

Best Practices

最佳实践

  1. Use environment variables for credentials, never hardcode
  2. Leverage auto-serialization - pass native JavaScript types
  3. Use TypeScript types for better type safety
  4. Set appropriate TTLs to manage memory
  5. Use pipelines for multiple operations
  6. Namespace your keys (e.g.,
    user:123
    ,
    session:abc
    )
  1. 使用环境变量存储凭证,切勿硬编码
  2. 利用自动序列化 - 直接传入原生 JavaScript 类型
  3. 使用 TypeScript 类型提升类型安全性
  4. 设置合适的 TTL以管理内存
  5. 使用管道处理多个操作
  6. 为键设置命名空间(例如:
    user:123
    session:abc

Resources

资源

Getting Help

获取帮助

For detailed information on specific topics, refer to the individual skill files in the
skills/
directory. Each file contains comprehensive examples, use cases, and best practices for its topic.
如需特定主题的详细信息,请参考
skills/
目录中的各个技能文件。每个文件都包含对应主题的全面示例、用例与最佳实践。