TITLE: Getting a value with Redis in Python DESCRIPTION: This snippet demonstrates how to use a Python Redis client to first set a value for a key using `set` and then retrieve it using `get`. It asserts that the retrieved value matches the one that was set. Requires a configured Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/get.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.set("key", "value") assert redis.get("key") == "value" ``` ---------------------------------------- TITLE: Execute Basic Redis Set/Get Commands - Python DESCRIPTION: Illustrates how to perform fundamental Redis operations, specifically setting a key's value (`set`) and retrieving a key's value (`get`), using the initialized Upstash Redis client. Examples are provided for both synchronous and asynchronous client instances. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/gettingstarted.mdx#_snippet_3 LANGUAGE: python CODE: ``` from upstash_redis import Redis redis = Redis.from_env() def main(): redis.set("a", "b") print(redis.get("a")) ``` LANGUAGE: python CODE: ``` from upstash_redis.asyncio import Redis redis = Redis.from_env() async def main(): await redis.set("a", "b") print(await redis.get("a")) ``` ---------------------------------------- TITLE: Setting a Key Basic Usage TypeScript DESCRIPTION: Demonstrates the basic usage of the Upstash Redis client's `set` command. It sets a key named "my-key" with a JavaScript object value, which the client automatically stringifies to JSON before storing. No options are provided. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/set.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.set("my-key", {my: "value"}); ``` ---------------------------------------- TITLE: Incrementing Feature Votes in Redis and Tracking IPs in Next.js API DESCRIPTION: This Next.js API route (`/api/vote`) processes user votes for features. It connects to Redis using `ioredis` and extracts the user's IP address from request headers. It then attempts to add this IP to a Redis Set keyed by the feature title (e.g., "s:Feature Title") using `SADD`. If the `SADD` command returns 1 (meaning the IP was added, indicating a unique vote from this IP for this feature), it increments the feature's score in the "roadmap" Sorted Set using `ZINCRBY`. If `SADD` returns 0, it means the IP was already present, and an error is returned to prevent duplicate votes. Requires a `REDIS_URL` and `fixUrl`. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/roadmapvotingapp.mdx#_snippet_3 LANGUAGE: javascript CODE: ``` import Redis from "ioredis"; import { fixUrl } from "./utils"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); const body = req.body; const title = body["title"]; let ip = req.headers["x-forwarded-for"] || req.headers["Remote_Addr"] || "NA"; let c = ip === "NA" ? 1 : await redis.sadd("s:" + title, ip); if (c === 0) { redis.quit(); res.json({ error: "You can not vote an item multiple times", }); } else { let v = await redis.zincrby("roadmap", 1, title); redis.quit(); res.json({ body: v, }); } }; ``` ---------------------------------------- TITLE: Create Redis Counter View in Django Python DESCRIPTION: Defines a Django view function `index` that initializes an Upstash Redis client from environment variables, increments a key named 'counter', and returns an HTTP response displaying the incremented count. Requires `django.http.HttpResponse` and `upstash_redis.Redis`. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/django.mdx#_snippet_3 LANGUAGE: python CODE: ``` from django.http import HttpResponse from upstash_redis import Redis redis = Redis.from_env() def index(request): count = redis.incr('counter') return HttpResponse(f'Page visited {count} times.') ``` ---------------------------------------- TITLE: Executing Redis Pipeline TypeScript DESCRIPTION: Demonstrates creating a Redis pipeline using `redis.pipeline()`, adding multiple commands (`set`, `get`), and executing the batch with `await p.exec()`. Pipelines are not atomic, meaning other commands from other clients might run in between commands within the pipeline. It returns an array containing the results of each executed command. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/transaction.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` const p = redis.pipeline(); p.set("foo", "bar"); p.get("foo"); const res = await p.exec(); ``` ---------------------------------------- TITLE: Performing Basic Redis Operations with Upstash Redis - Typescript DESCRIPTION: Demonstrates initializing the @upstash/redis client using a URL and token, then shows examples of common Redis commands like set, get, zadd, zrange, lpush, lrange, hset, hget, sadd, and spop for different data types. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/getstarted.mdx#_snippet_4 LANGUAGE: Typescript CODE: ``` import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // string await redis.set('key', 'value'); let data = await redis.get('key'); console.log(data) await redis.set('key2', 'value2', {ex: 1}); // sorted set await redis.zadd('scores', { score: 1, member: 'team1' }) data = await redis.zrange('scores', 0, 100 ) console.log(data) // list await redis.lpush('elements', 'magnesium') data = await redis.lrange('elements', 0, 100 ) console.log(data) // hash await redis.hset('people', {name: 'joe'}) data = await redis.hget('people', 'name' ) console.log(data) // sets await redis.sadd('animals', 'cat') data = await redis.spop('animals', 1) console.log(data) ``` ---------------------------------------- TITLE: Incrementing a Redis Key using TypeScript DESCRIPTION: This snippet demonstrates how to set an initial integer value for a Redis key and then increment it using the `incr` command, illustrating the command's behavior and the expected return value. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/incr.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.set("key", 6); await redis.incr("key"); // returns 7 ``` ---------------------------------------- TITLE: Implementing FastAPI Weather Endpoint with Redis Caching Python DESCRIPTION: Defines a FastAPI application (`app`) with a GET endpoint (`/weather/{city}`). This endpoint first checks Redis for cached data using the city name as the key. If data is found, it's returned from the cache; otherwise, it fetches data from an external weather API, stores it in Redis with a 10-minute expiration (600 seconds), and then returns the data. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_fastapi_caching.mdx#_snippet_3 LANGUAGE: Python CODE: ``` from fastapi import FastAPI from upstash_redis import Redis import requests import os app = FastAPI() # Connect to Redis using environment variables redis = Redis.from_env() # Mock API endpoint for weather data WEATHER_API_URL = "https://api.weatherapi.com/v1/current.json" API_KEY = os.getenv("WEATHER_API_KEY") @app.get("/weather/{city}") def get_weather(city: str): cache_key = f"weather:{city}" # Check if the data exists in cache cached_data = redis.get(cache_key) if cached_data: return {"source": "cache", "data": cached_data} # Fetch data from external API response = requests.get(f"{WEATHER_API_URL}?key={API_KEY}&q={city}") weather_data = response.json() # Store the data in Redis cache with a 10-minute expiration redis.setex(cache_key, 600, weather_data) return {"source": "api", "data": weather_data} ``` ---------------------------------------- TITLE: Implementing Redis Counter in Next.js Homepage (TSX) DESCRIPTION: The code for the main page component (`app/page.tsx`) in a Next.js App Router project. It initializes the `@upstash/redis` client from environment variables, uses `redis.incr()` to atomically increment a key named "counter" in Redis, and displays the updated counter value on the page. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/nextjs_with_redis.mdx#_snippet_3 LANGUAGE: TSX CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ``` ---------------------------------------- TITLE: Connecting and Executing Commands with redis-cli (Bash) DESCRIPTION: This snippet demonstrates how to connect to an Upstash Redis database using the `redis-cli` tool over TLS and execute common Redis commands like `SET`, `GET`, and `INCR`. It requires the database endpoint, port, and password. The output shows successful command execution and return values. SOURCE: https://github.com/upstash/docs/blob/main/redis/overall/getstarted.mdx#_snippet_0 LANGUAGE: bash CODE: ``` > redis-cli --tls -a PASSWORD -h ENDPOINT -p PORT ENDPOINT:PORT> set counter 0 OK ENDPOINT:PORT> get counter "0" ENDPOINT:PORT> incr counter (int) 1 ENDPOINT:PORT> incr counter (int) 2 ``` ---------------------------------------- TITLE: Initialize Upstash Redis Python Client from Environment Variables DESCRIPTION: Shows how to initialize the Upstash Redis client (synchronous and asynchronous) by automatically loading the necessary credentials (`UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`) from environment variables using the `from_env()` class method. This approach is often preferred for managing secrets. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/gettingstarted.mdx#_snippet_2 LANGUAGE: python CODE: ``` # for sync use from upstash_redis import Redis redis = Redis.from_env() ``` LANGUAGE: python CODE: ``` # for async use from upstash_redis.asyncio import Redis redis = Redis.from_env() ``` ---------------------------------------- TITLE: Initializing Upstash Redis Client in Node.js/Browser (TypeScript) DESCRIPTION: Demonstrates the standard way to initialize the Upstash Redis client in Node.js or browser environments. It shows how to pass the URL and token explicitly or load them automatically from the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN environment variables using `fromEnv()`. Requires the `@upstash/redis` package. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/deployment.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // or load directly from env const redis = Redis.fromEnv() ``` ---------------------------------------- TITLE: Implementing Server-Side Counter with Upstash Redis TSX DESCRIPTION: Demonstrates how to use `getServerSideProps` in Next.js Pages Router to fetch data server-side. It initializes an `@upstash/redis` client using environment variables, increments a key named "counter" in Redis, and passes the new count as props to the React component for display. Requires `@upstash/redis` and `next` dependencies and configured environment variables. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/nextjs-pages-router.mdx#_snippet_2 LANGUAGE: TSX CODE: ``` import type { InferGetServerSidePropsType, GetServerSideProps } from 'next' import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export const getServerSideProps = (async () => { const count = await redis.incr("counter"); return { props: { count } } }) satisfies GetServerSideProps<{ count: number }> export default function Home({ count, }: InferGetServerSidePropsType) { return (

Counter: {count}

) } ``` ---------------------------------------- TITLE: Handling HTTP Requests and Incrementing Redis Counter in Deno Deploy - Typescript DESCRIPTION: This Typescript snippet sets up a basic HTTP server in Deno Deploy using `deno.land/std/http`. It initializes an Upstash Redis client with placeholder URL and token, increments a counter key named "deno-counter" in Redis for every request (except favicon), and returns the current counter value as a JSON response. It requires the `http/server` and `upstash_redis` Deno modules. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/deno-deploy.mdx#_snippet_0 LANGUAGE: Typescript CODE: ``` import { serve } from "https://deno.land/std@0.142.0/http/server.ts"; import { Redis } from "https://deno.land/x/upstash_redis@v1.14.0/mod.ts"; serve(async (_req: Request) => { if (!_req.url.endsWith("favicon.ico")) { const redis = new Redis({ url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN", }); const counter = await redis.incr("deno-counter"); return new Response(JSON.stringify({ counter }), { status: 200 }); } }); ``` ---------------------------------------- TITLE: Removing Keys Basic - Upstash Redis TypeScript DESCRIPTION: Demonstrates the basic usage of the `del` command using the Upstash Redis client in TypeScript. It shows how to delete specific keys by passing them as arguments. Requires an initialized Upstash Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/del.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.del("key1", "key2"); ``` ---------------------------------------- TITLE: Getting Hash Field Value using Upstash Redis Client (TypeScript) DESCRIPTION: This snippet illustrates how to use the Upstash Redis client in TypeScript to first set a hash field and then retrieve its value using the `hget` command. It shows the typical asynchronous call pattern and logs the retrieved value, demonstrating the command's functionality. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hget.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.hset("key", {field: "value"}); const field = await redis.hget("key", "field"); console.log(field); // "value" ``` ---------------------------------------- TITLE: Using INCRBY with Upstash Redis Client in Python DESCRIPTION: This snippet demonstrates the usage of the Redis INCRBY command using a Python client. It first initializes a key with an integer value using SET, then calls INCRBY to increment that value by a specified number, and finally asserts the resulting value. It requires a connected Redis client instance named `redis`. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/incrby.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.set("key", 6) assert redis.incrby("key", 4) == 10 ``` ---------------------------------------- TITLE: Implementing Supabase Function Counter with Upstash Redis - TypeScript DESCRIPTION: Provides the core TypeScript code for the Supabase Edge Function. It sets up an HTTP server, initializes an Upstash Redis client using environment variables (UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN), increments a Redis hash key ('supa-edge-counter') based on the 'DENO_REGION' environment variable or 'localhost', retrieves the full hash, sorts it, calculates a total, and returns the regional counts and total in a JSON response. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/supabase.mdx#_snippet_2 LANGUAGE: ts CODE: ``` import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; import { Redis } from "https://deno.land/x/upstash_redis@v1.19.3/mod.ts"; console.log(`Function "upstash-redis-counter" up and running!`); serve(async (_req) => { try { const redis = new Redis({ url: Deno.env.get("UPSTASH_REDIS_REST_URL")!, token: Deno.env.get("UPSTASH_REDIS_REST_TOKEN")!, }); const deno_region = Deno.env.get("DENO_REGION"); if (deno_region) { // Increment region counter await redis.hincrby("supa-edge-counter", deno_region, 1); } else { // Increment localhost counter await redis.hincrby("supa-edge-counter", "localhost", 1); } // Get all values const counterHash: Record | null = await redis.hgetall( "supa-edge-counter" ); const counters = Object.entries(counterHash!) .sort(([, a], [, b]) => b - a) // sort desc .reduce( (r, [k, v]) => ({ total: r.total + v, regions: { ...r.regions, [k]: v }, }), { total: 0, regions: {}, } ); return new Response(JSON.stringify({ counters }), { status: 200 }); } catch (error) { return new Response(JSON.stringify({ error: error.message }), { status: 200, }); } }); ``` ---------------------------------------- TITLE: Adding Elements to Redis List using RPUSH in TypeScript DESCRIPTION: This snippet demonstrates how to use the `redis.rpush` method to add elements to a Redis list. It shows pushing multiple elements initially and then a single element, logging the new length of the list after each operation. The method requires the list key and one or more elements to append. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/rpush.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` const length1 = await redis.rpush("key", "a", "b", "c"); console.log(length1); // 3 const length2 = await redis.rpush("key", "d"); console.log(length2); // 4 ``` ---------------------------------------- TITLE: Applying EXPIRE with Seconds and Timedelta (Python) DESCRIPTION: This Python snippet demonstrates how to set an expiration time on a Redis key using the `expire` method. It shows two common ways to specify the timeout: as an integer representing seconds or as a `datetime.timedelta` object. It also includes commands to set and retrieve the key to verify the expiration behavior. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/expire.mdx#_snippet_0 LANGUAGE: Python CODE: ``` # With seconds redis.set("mykey", "Hello") redis.expire("mykey", 5) assert redis.get("mykey") == "Hello" time.sleep(5) assert redis.get("mykey") is None # With a timedelta redis.set("mykey", "Hello") redis.expire("mykey", datetime.timedelta(seconds=5)) ``` ---------------------------------------- TITLE: Getting String Length using Upstash Redis Client TypeScript DESCRIPTION: This snippet demonstrates setting a string value in Redis and then using the `strlen` method from the `@upstash/redis` client to retrieve its length. It shows the basic sequence of setting a key and then querying its string value length, printing the result to the console. It assumes an initialized `redis` client instance is available. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/strlen.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.set("key", "helloworld") const length = await redis.strlen("key"); console.log(length); // 10 ``` ---------------------------------------- TITLE: Retrieving Bit using Redis TS DESCRIPTION: This snippet demonstrates how to retrieve a single bit value from a Redis key at a specified offset using the `redis.getbit` function. It requires a Redis client instance and the target key and offset as inputs. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/bitmap/getbit.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const bit = await redis.getbit(key, 4); ``` ---------------------------------------- TITLE: Conditional SET Command (nx, xx) in Python DESCRIPTION: Shows how to use the `nx` and `xx` options with the Redis SET command in Python to conditionally set a key based on its existence. `nx=True` sets only if the key does *not* exist, while `xx=True` sets only if it *does* exist. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/set.mdx#_snippet_1 LANGUAGE: python CODE: ``` # Only set the key if it does not already exist. assert redis.set("key", "value", nx=True) == False # Only set the key if it already exists. assert redis.set("key", "value", xx=True) == True ``` ---------------------------------------- TITLE: Calling Redis TOUCH Command (TypeScript) DESCRIPTION: Demonstrates how to execute the Redis TOUCH command using a Redis client instance in TypeScript. It takes one or more key names as arguments and updates their last access time, returning the count of keys that were successfully touched. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/touch.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.touch("key1", "key2", "key3"); ``` ---------------------------------------- TITLE: Implementing FastAPI Rate Limiting with Upstash Redis (Python) DESCRIPTION: This Python script (`main.py`) sets up a FastAPI application integrated with Upstash Redis for rate limiting. It initializes the Redis client from environment variables, creates a `Ratelimit` instance with a `FixedWindow` strategy allowing 10 requests per 10 seconds, defines a rate-limited GET endpoint (`/expensive_calculation`), and includes helper functions for simulation and local testing. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_rate_limiting.mdx#_snippet_2 LANGUAGE: python CODE: ``` from fastapi import FastAPI, HTTPException from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis from dotenv import load_dotenv import requests # Load environment variables from .env file load_dotenv() # Initialize the FastAPI app app = FastAPI() # Initialize Redis client redis = Redis.from_env() # Create a rate limiter that allows 10 requests per 10 seconds ratelimit = Ratelimit( redis=redis, limiter=FixedWindow(max_requests=10, window=10), # 10 requests per 10 seconds prefix="@upstash/ratelimit" ) @app.get("/expensive_calculation") def expensive_calculation(): identifier = "api" # Common identifier for rate limiting all users equally response = ratelimit.limit(identifier) if not response.allowed: raise HTTPException(status_code=429, detail="Rate limit exceeded. Please try again later.") # Placeholder for a resource-intensive operation result = do_expensive_calculation() return {"message": "Here is your result", "result": result} # Simulated function for an expensive calculation def do_expensive_calculation(): return "Expensive calculation result" # Test function to check rate limiting def test_rate_limiting(): url = "http://127.0.0.1:8000/expensive_calculation" success_count = 0 fail_count = 0 # Attempt 15 requests in quick succession for i in range(15): response = requests.get(url) if response.status_code == 200: success_count += 1 print(f"Request {i+1}: Success - {response.json()['message']}") elif response.status_code == 429: fail_count += 1 print(f"Request {i+1}: Failed - Rate limit exceeded") # Small delay to avoid flooding print("\nTest Summary:") print(f"Total Successful Requests: {success_count}") print(f"Total Failed Requests due to Rate Limit: {fail_count}") if __name__ == "__main__": # Run the FastAPI app in a separate thread or terminal with: # uvicorn main:app --reload # To test rate limiting after the server is running test_rate_limiting() ``` ---------------------------------------- TITLE: Configuring Upstash Redis Environment Variables DESCRIPTION: This snippet shows the required environment variables (UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN) that need to be added to the .env file. These variables contain the connection details for the Upstash Redis database, which are necessary for the application to communicate with Redis. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/nextjs-app-router.mdx#_snippet_1 LANGUAGE: env CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Initializing Upstash Redis Client in Cloudflare Worker (TypeScript) DESCRIPTION: This snippet demonstrates how to initialize the @upstash/redis/cloudflare client within a Cloudflare Worker using environment variables. It defines the expected environment variables (UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN) and shows a basic fetch handler that increments a Redis counter and returns the value. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/cloudflareworkers.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis/cloudflare"; export interface Env { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string; } export default { async fetch( request: Request, env: Env, ctx: ExecutionContext ): Promise { const redis = Redis.fromEnv(env); const count = await redis.incr("counter"); return new Response(JSON.stringify({ count })); }, }; ``` ---------------------------------------- TITLE: Initializing Regional Fixed Window Ratelimit (TypeScript) DESCRIPTION: Initializes a regional Ratelimit instance using the fixedWindow algorithm. It connects to Redis via `Redis.fromEnv()` and configures the limiter to allow 10 requests per 10 seconds for each identifier. Requires the `@upstash/ratelimit` and `@upstash/redis` libraries. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/algorithms.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.fixedWindow(10, "10 s"), }); ``` ---------------------------------------- TITLE: AWS Lambda Function Handler (Node.js) DESCRIPTION: This Node.js code in `handler.js` implements the core logic for the Lambda functions. It initializes a Redis client, defines CORS headers, and contains two exported asynchronous functions: `get` retrieves data from Redis, builds a histogram, and returns it, while `record` parses request body, adds values to a Redis list, and returns a success message. A helper `fixUrl` function adjusts the Redis URL format. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/histogram.mdx#_snippet_4 LANGUAGE: javascript CODE: ``` const hdr = require("hdr-histogram-js"); const Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis(fixUrl(process.env.REDIS_URL)); } const headers = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": true, }; const SIZE = 10000; module.exports.get = async (event) => { if (!event.queryStringParameters || !event.queryStringParameters.name) { return { statusCode: 400, headers: headers, body: JSON.stringify({ message: "Invalid parameters. Name is needed.", }), }; } const name = event.queryStringParameters.name; const data = await client.lrange(name, 0, SIZE); const histogram = hdr.build(); data.forEach((item) => { histogram.recordValue(item); }); return { statusCode: 200, body: JSON.stringify({ histogram: histogram, }), }; }; module.exports.record = async (event) => { let body = JSON.parse(event.body); if (!body || !body.name || !body.values) { return { statusCode: 400, headers: headers, body: JSON.stringify({ message: "Invalid parameters. Name and values are needed.", }), }; } const name = body.name; const values = body.values; await client.lpush(name, values); return { statusCode: 200, body: JSON.stringify({ message: "Success", name: name, }), }; }; function fixUrl(url) { if (!url) { return ""; } if (url.startsWith("redis://") && !url.startsWith("redis://:")) { return url.replace("redis://", "redis://:"); } if (url.startsWith("rediss://") && !url.startsWith("rediss://:")) { return url.replace("rediss://", "rediss://:"); } return url; } ``` ---------------------------------------- TITLE: Iterating through Redis Keys using SCAN in Python DESCRIPTION: This Python snippet demonstrates how to retrieve all keys from a Redis database using the `SCAN` command via a Redis client library. It initializes a cursor to 0, iteratively calls the `redis.scan` method with the previous cursor and a `match` pattern (`*` for all keys), appends the returned keys to a list, and continues until the cursor returned by `scan` is 0, indicating the end of the iteration. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/scan.mdx#_snippet_0 LANGUAGE: Python CODE: ``` # Get all keys cursor = 0 results = [] while True: cursor, keys = redis.scan(cursor, match="*") results.extend(keys) if cursor == 0: break ``` ---------------------------------------- TITLE: Configuring Redis Connection in .env (Env) DESCRIPTION: Sets the Redis connection details (host, port, password) in the Laravel environment file (.env) using values obtained from the Upstash Console. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/laravel_caching.mdx#_snippet_1 LANGUAGE: env CODE: ``` REDIS_HOST="" REDIS_PORT=6379 REDIS_PASSWORD="" ``` ---------------------------------------- TITLE: Configuring Upstash Redis Connection .env DESCRIPTION: Shows the format for defining the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables in a `.env` file. These variables are necessary for the application to connect to the Upstash Redis database using REST. Requires obtaining the URL and token from the Upstash console or CLI. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/nextjs-pages-router.mdx#_snippet_1 LANGUAGE: .env CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Configuring Upstash Redis Credentials - .env - Shell DESCRIPTION: This snippet shows the format for adding your Upstash Redis REST URL and REST Token to the project's `.env` file. These environment variables are automatically picked up by the `@upstash/redis` client when using `Redis.fromEnv()`. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/vercel-functions-app-router.mdx#_snippet_1 LANGUAGE: Shell CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Set Environment Variables in .env.local DESCRIPTION: Example of how to add the required Upstash Redis environment variables (`UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`) in a local `.env.local` file for development. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/gettingstarted.mdx#_snippet_6 LANGUAGE: env CODE: ``` UPSTASH_REDIS_REST_URL=**** UPSTASH_REDIS_REST_TOKEN=**** ``` ---------------------------------------- TITLE: Implementing Leaderboard Logic (Javascript) DESCRIPTION: This Javascript code for a Cloudflare Worker defines how to handle incoming fetch requests. It routes GET requests to getLeaderboard and POST requests to addScore, interacting with an Upstash Redis database via its REST API. The getLeaderboard function includes Cloudflare edge caching configuration. Required dependencies are the Cloudflare Workers environment and Upstash Redis REST endpoint/token. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/edge_leaderboard.mdx#_snippet_1 LANGUAGE: javascript CODE: ``` addEventListener("fetch", (event) => { event.respondWith(handleRequest(event.request)); }); async function handleRequest(request) { if (request.method === "GET") { return getLeaderboard(); } else if (request.method === "POST") { return addScore(request); } else { return new Response("Invalid Request!"); } } async function getLeaderboard() { let url = "https://us1-full-bug-31874.upstash.io/zrevrange/scores/0/1000/WITHSCORES/?_token=" + TOKEN; let res = await fetch(new Request(url), { cf: { cacheTtl: 10, cacheEverything: true, cacheKey: url, }, }); return res; } async function addScore(request) { const { searchParams } = new URL(request.url); let player = searchParams.get("player"); let score = searchParams.get("score"); let url = "https://us1-full-bug-31874.upstash.io/zadd/scores/" + score + "/" + player + "?_token=" + TOKEN; let res = await fetch(url); return new Response(await res.text()); } ``` ---------------------------------------- TITLE: Setting Up Express App with Redis Session Store - Javascript DESCRIPTION: This JavaScript code sets up an Express application, integrates Redis for session storage using connect-redis, and implements a simple view counter that stores session data in Redis. It requires the Express, Redis, connect-redis, and express-session libraries. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/cloud_run_sessions.mdx#_snippet_3 LANGUAGE: javascript CODE: ``` var express = require("express"); var parseurl = require("parseurl"); var session = require("express-session"); const redis = require("redis"); var RedisStore = require("connect-redis")(session); var client = redis.createClient({ // REPLACE HERE }); var app = express(); app.use( session({ store: new RedisStore({ client: client }), secret: "forest squirrel", resave: false, saveUninitialized: true, }) ); app.use(function (req, res, next) { if (!req.session.views) { req.session.views = {}; } // get the url pathname var pathname = parseurl(req).pathname; // count the views req.session.views[pathname] = (req.session.views[pathname] || 0) + 1; next(); }); app.get("/", function (req, res, next) { res.send("you viewed this page " + req.session.views["/"] + " times"); }); app.get("/foo", function (req, res, next) { res.send("you viewed this page " + req.session.views["/foo"] + " times"); }); app.get("/bar", function (req, res, next) { res.send("you viewed this page " + req.session.views["/bar"] + " times"); }); app.listen(8080, function () { console.log("Example app listening on port 8080!"); }); ``` ---------------------------------------- TITLE: Recommended Batching with Promise.all and Auto-Pipelining (TypeScript) DESCRIPTION: Illustrates the recommended approach for efficient batching with auto-pipelining by grouping multiple Redis commands within Promise.all. This ensures that all commands are sent in a single pipeline execution. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/pipelining/auto-pipeline.mdx#_snippet_3 LANGUAGE: TypeScript CODE: ``` // makes a single PIPELINE call: const [ foo, bar ] = await Promise.all([ redis.get("foo"), redis.get("bar") ]) ``` ---------------------------------------- TITLE: Implementing URL Shortener Logic - Python DESCRIPTION: Python script implementing the URL shortener functionality. It connects to Redis using environment variables, generates random short codes, stores URL mappings with expiration times, and retrieves original URLs. Requires `upstash-redis` and `python-dotenv` libraries. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_url_shortener.mdx#_snippet_2 LANGUAGE: python CODE: ``` import string import random from upstash_redis import Redis from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Redis connection redis = Redis.from_env() # Characters to generate the short URL from CHARS = string.ascii_letters + string.digits BASE_URL = "https://short.url/" # Function to generate a random string for the short URL def generate_short_code(length=6): return ''.join(random.choices(CHARS, k=length)) # Function to shorten the URL with an expiration time def shorten_url(url, expiration=3600): # Generate a random short code short_code = generate_short_code() # Save the short code in Redis redis.set(short_code, url, ex=expiration) return BASE_URL + short_code # Function to get the original URL from the short URL def get_original_url(short_code): return redis.get(short_code) # Example usage if __name__ == "__main__": original_url = "https://example.com/my-very-long-url" # Shorten the URL short_url = shorten_url(original_url, expiration=600) print(f"Shortened URL: {short_url}") # Get the original URL original_url = get_original_url(short_url.split("/")[-1]) if original_url: print(f"Original URL: {original_url}") else: print("Short URL expired or not found") ``` ---------------------------------------- TITLE: Iterating through Set Members using SSCAN in Python DESCRIPTION: This code snippet demonstrates how to use the Redis SSCAN command in Python to retrieve all members of a set incrementally. It utilizes a loop that starts with a cursor of 0 and continues calling SSCAN with the returned cursor until the server returns a cursor of 0, indicating the completion of the iteration. It requires a Python Redis client library. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/sscan.mdx#_snippet_0 LANGUAGE: python CODE: ``` # Get all members of a set. cursor = 0 results = set() while True: cursor, keys = redis.sscan("myset", cursor, match="*") results.extend(keys) if cursor == 0: break ``` ---------------------------------------- TITLE: Connecting Redis-py Client (Python) DESCRIPTION: This snippet illustrates how to connect the `redis-py` client to an Upstash Redis database. It shows initializing the `Redis` object by providing host, port, and password as parameters, explicitly enabling SSL (`ssl=True`) which is required for Upstash. The example then sets and retrieves a key. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/connectclient.mdx#_snippet_2 LANGUAGE: python CODE: ``` import redis r = redis.Redis( host= 'YOUR_ENDPOINT', port= 'YOUR_PORT', password= 'YOUR_PASSWORD', ssl=True) r.set('foo','bar') print(r.get('foo')) ``` ---------------------------------------- TITLE: Executing Upstash Redis Pipeline - TypeScript DESCRIPTION: This snippet demonstrates how to use the `pipeline()` method to create a sequence of commands that are sent to Upstash Redis in a single request. Commands are added by chaining method calls onto the pipeline instance. The `exec()` method sends the batch and returns an array containing the results of each command in order. Note that pipeline execution is not atomic. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/pipelining/pipeline-transaction.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis"; const redis = new Redis({ /* auth */ }); const p = redis.pipeline(); // Now you can chain multiple commands to create your pipeline: p.set("key", 2); p.incr("key"); // or inline: p.hset("key2", "field", { hello: "world" }).hvals("key2"); // Execute the pipeline once you are done building it: // `exec` returns an array where each element represents the response of a command in the pipeline. // You can optionally provide a type like this to get a typed response. const res = await p.exec<[Type1, Type2, Type3]>(); ``` ---------------------------------------- TITLE: Implement FastAPI Session Management with Redis DESCRIPTION: This Python code implements a simple FastAPI application (`main.py`) with endpoints for user login, accessing a profile, and logging out. It uses `upstash-redis` to store session data and manages session state using cookies, implementing a sliding expiration mechanism where the session timeout is reset on each request. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_session.mdx#_snippet_2 LANGUAGE: python CODE: ``` from fastapi import FastAPI, Response, Cookie, HTTPException from pydantic import BaseModel from upstash_redis import Redis from dotenv import load_dotenv import uuid # Load environment variables load_dotenv() redis = Redis.from_env() app = FastAPI() SESSION_TIMEOUT_SECONDS = 900 # 15 minutes # Define the request body model for login class LoginRequest(BaseModel): username: str @app.post("/login/") async def login(request: LoginRequest, response: Response): session_id = str(uuid.uuid4()) redis.hset(f"session:{session_id}", values={"user": request.username, "status": "active"}) redis.expire(f"session:{session_id}", SESSION_TIMEOUT_SECONDS) response.set_cookie(key="session_id", value=session_id, httponly=True) return {"message": "Logged in successfully", "session_id": session_id} @app.get("/profile/") async def get_profile(session_id: str = Cookie(None)): if not session_id: raise HTTPException(status_code=403, detail="No session cookie found") session_data = redis.hgetall(f"session:{session_id}") if not session_data: response = Response() response.delete_cookie(key="session_id") # Clear the expired cookie raise HTTPException(status_code=404, detail="Session expired") # Update the session expiration time (sliding expiration) redis.expire(f"session:{session_id}", SESSION_TIMEOUT_SECONDS) return {"session_id": session_id, "session_data": session_data} @app.post("/logout/") async def logout(response: Response, session_id: str = Cookie(None)): if session_id: redis.delete(f"session:{session_id}") response.delete_cookie(key="session_id") return {"message": "Logged out successfully"} ``` ---------------------------------------- TITLE: Install upstash-redis package using npm - Bash DESCRIPTION: Provides the command-line instruction to install the `@upstash/redis` library using the npm package manager. This is the first step required before using the client in a project. Requires npm and Node.js installed. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/connectwithupstashredis.mdx#_snippet_0 LANGUAGE: bash CODE: ``` npm install @upstash/redis ``` ---------------------------------------- TITLE: Installing Upstash Redis with npm - Bash DESCRIPTION: Provides the command to install the NPM-compatible version of the @upstash/redis library using the npm package manager. This is suitable for Node.js environments or projects managed with npm. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/getstarted.mdx#_snippet_1 LANGUAGE: Bash CODE: ``` npm install @upstash/redis ``` ---------------------------------------- TITLE: Executing Upstash Redis Transaction - TypeScript DESCRIPTION: This snippet shows how to use the `multi()` method to initiate a transaction, which guarantees that the commands are executed atomically. Similar to pipelines, commands are added by chaining, and `exec()` is used to send the transaction block to Upstash Redis for atomic processing. The result is an array containing the outcomes of the commands if the transaction succeeds. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/pipelining/pipeline-transaction.mdx#_snippet_1 LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis"; const redis = new Redis({ /* auth */ }); const p = redis.multi(); p.set("key", 2); p.incr("key"); // or inline: p.hset("key2", "field", { hello: "world" }).hvals("key2"); // execute the transaction const res = await p.exec<[Type1, Type2, Type3]>(); ``` ---------------------------------------- TITLE: Implementing Counter Function Logic (JavaScript) DESCRIPTION: Implements the serverless function (`counter`) using Node.js and the `@upstash/redis` client. It initializes the Redis client from environment variables, increments a key named "counter", and returns the updated count in an HTTP response. Depends on `@upstash/redis` and requires environment variables for Redis connection. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/using_serverless_framework.mdx#_snippet_6 LANGUAGE: javascript CODE: ``` const { Redis } = require('@upstash/redis'); const redis = Redis.fromEnv(); exports.counter = async (event) => { const count = await redis.incr("counter"); return { statusCode: 200, body: JSON.stringify('Counter: ' + count), }; }; ``` ---------------------------------------- TITLE: Initialize and Use Upstash Redis Client (Explicit Config) - TypeScript DESCRIPTION: Shows how to initialize the `upstash-redis` client by providing the REST URL and token directly to the constructor. It includes an asynchronous function to demonstrate a simple `get` operation and basic error handling. Requires `@upstash/redis` installed and valid Upstash Redis REST credentials. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/connectwithupstashredis.mdx#_snippet_1 LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis"; const redis = new Redis({ url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN", }); (async () => { try { const data = await redis.get("key"); console.log(data); } catch (error) { console.error(error); } })(); ``` ---------------------------------------- TITLE: Iterating All Hash Fields using HSCAN (Python) DESCRIPTION: This snippet demonstrates how to use the `redis.hscan` method in Python to retrieve all fields from a Redis hash key. It shows a loop structure that utilizes the cursor returned by each call to continue the iteration until the cursor is 0, indicating the scan is complete. The results are collected in a list. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hscan.mdx#_snippet_0 LANGUAGE: python CODE: ``` cursor = 0 results = [] while True: cursor, keys = redis.hscan("myhash", cursor, match="*") results.extend(keys) if cursor == 0: break ``` ---------------------------------------- TITLE: Implement Autocomplete Query Logic Node.js DESCRIPTION: Defines the AWS Lambda handler function `query` for the autocomplete API. It connects to Redis, extracts the search term from query parameters, uses ZRANK and ZRANGE to find matching terms in the 'terms' sorted set, filters results, and returns a JSON response. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/auto_complete_with_serverless_redis.mdx#_snippet_4 LANGUAGE: javascript CODE: ``` var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis(process.env.REDIS_URL); } const headers = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": true, }; module.exports.query = async (event, context, callback) => { if (!event.queryStringParameters || !event.queryStringParameters.term) { return { statusCode: 400, headers: headers, body: JSON.stringify({ message: "Invalid parameters. Term needed as query param.", }), }; } let term = event.queryStringParameters.term.toUpperCase(); let res = []; let rank = await client.zrank("terms", term); if (rank != null) { let temp = await client.zrange("terms", rank, rank + 100); for (const el of temp) { if (!el.startsWith(term)) { break; } if (el.endsWith("*")) { res.push(el.substring(0, el.length - 1)); } else { // Include the prefix itself if it exists in the set (though likely not in final results) // Depending on the algorithm nuances, you might adjust this part } } } return { statusCode: 200, headers: headers, body: JSON.stringify({ message: "Query:" + event.queryStringParameters.term, result: res, }), }; }; ``` ---------------------------------------- TITLE: Connecting IORedis Client (JavaScript) DESCRIPTION: This snippet demonstrates how to connect the `ioredis` client to an Upstash Redis database in Node.js using a connection string. The `rediss://` scheme indicates an SSL connection, followed by authentication details (password) and the endpoint and port. It includes examples of setting and getting a key. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/connectclient.mdx#_snippet_1 LANGUAGE: javascript CODE: ``` const Redis = require("ioredis"); let client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); await client.set("foo", "bar"); let x = await client.get("foo"); console.log(x); ``` ---------------------------------------- TITLE: Using Cache::remember Method (PHP) DESCRIPTION: Demonstrates how to use Laravel's `Cache::remember` method to retrieve data from the cache or execute a closure and store the result if the cache key does not exist, with a specified expiration time. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/laravel_caching.mdx#_snippet_13 LANGUAGE: php CODE: ``` $value = Cache::remember('todos', $seconds, function () { return Todo::all(); }); ``` ---------------------------------------- TITLE: Installing Node.js Dependencies (Shell) DESCRIPTION: Executes the npm install command to download and install the packages listed in the `dependencies` section of the `package.json` file. This makes the `@upstash/redis` library available for use in the project. Requires Node.js and npm installed. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/using_serverless_framework.mdx#_snippet_4 LANGUAGE: shell CODE: ``` npm install ``` ---------------------------------------- TITLE: Connecting Jedis Client (Java) DESCRIPTION: This snippet demonstrates connecting the `jedis` client to an Upstash Redis database in Java. It shows creating a `Jedis` instance with the endpoint and port, enabling SSL/TLS via a boolean parameter, authenticating using the `auth` method with the password, and performing basic `set` and `get` operations. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/connectclient.mdx#_snippet_3 LANGUAGE: java CODE: ``` Jedis jedis = new Jedis("YOUR_ENDPOINT", "YOUR_PORT", true); jedis.auth("YOUR_PASSWORD"); jedis.set("foo", "bar"); String value = jedis.get("foo"); System.out.println(value); ``` ---------------------------------------- TITLE: Manage Redis Connections in Serverless Function - JavaScript DESCRIPTION: This JavaScript snippet demonstrates efficient Redis connection management within a serverless function handler. It shows initializing the 'ioredis' client, performing database operations (placeholder), and explicitly closing the connection using `client.quit()` before the function completes. This pattern helps avoid exceeding concurrent connection limits by preventing connections from lingering after the function execution finishes. It requires the 'ioredis' library and the Redis connection string available via `process.env.REDIS_URL`. SOURCE: https://github.com/upstash/docs/blob/main/redis/troubleshooting/max_concurrent_connections.mdx#_snippet_0 LANGUAGE: javascript CODE: ``` exports.handler = async (event) => { const client = new Redis(process.env.REDIS_URL); /* do stuff with redis */ await client.quit(); /* do other stuff */ return { response: "response", }; }; ``` ---------------------------------------- TITLE: Querying Multiple Set Members in Redis (TypeScript) DESCRIPTION: This snippet demonstrates how to use the `redis.smismember` command in TypeScript. It first adds members to a set using `redis.sadd`, then calls `smismember` with the set key and an array of members to check, and finally logs the resulting array indicating member presence (1) or absence (0). It requires a connected Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/smismember.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.sadd("set", "a", "b", "c"); const members = await redis.smismember("set", ["a", "b", "d"]); console.log(members); // [1, 1, 0] ``` ---------------------------------------- TITLE: Implementing Upstash Redis Counter Function - TypeScript DESCRIPTION: This TypeScript code defines an Azure HTTP triggered function that interacts with Upstash Redis. It initializes the Redis client using environment variables for connection details, increments a key named 'counter' upon execution, and returns the new count in the HTTP response body. It requires the `@azure/functions` and `@upstash/redis` packages. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/azure-functions.mdx#_snippet_3 LANGUAGE: typescript CODE: ``` import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions"; import { Redis } from "@upstash/redis"; const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN }); export async function CounterFunction(request: HttpRequest, context: InvocationContext): Promise { const count = await redis.incr("counter"); return { status: 200, body: `Counter: ${count}` }; }; app.http('CounterFunction', { methods: ['GET', 'POST'], authLevel: 'anonymous', handler: CounterFunction }); ``` ---------------------------------------- TITLE: Wait for Pending Operations in Serverless DESCRIPTION: Shows how to use the `context.waitUntil` method available in serverless environments (like Cloudflare Workers or Vercel Edge Functions) with the `pending` promise from the `ratelimit.limit` method to ensure background tasks complete before the function exits. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/gettingstarted.mdx#_snippet_7 LANGUAGE: ts CODE: ``` const { pending } = await ratelimit.limit("id"); context.waitUntil(pending); ``` ---------------------------------------- TITLE: Installing Upstash Redis Client - Shell DESCRIPTION: This command uses npm (Node Package Manager) to install the `@upstash/redis` client library as a dependency in the current project. This package is required to interact with the Upstash Redis database. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/azure-functions.mdx#_snippet_1 LANGUAGE: shell CODE: ``` npm install @upstash/redis ``` ---------------------------------------- TITLE: Implementing Redis transactions in Python DESCRIPTION: Demonstrates how to create a Redis transaction using `redis.multi()` to batch multiple commands that are executed atomically. Commands are added to the transaction object and executed with `exec()`, returning results similar to a pipeline but with atomicity guarantees. Requires an initialized `redis` client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/features.mdx#_snippet_3 LANGUAGE: python CODE: ``` pipeline = redis.multi() pipeline.set("foo", 1) pipeline.incr("foo") pipeline.get("foo") result = pipeline.exec() print(result) # prints [True, 2, '2'] ``` ---------------------------------------- TITLE: Connecting to Upstash Redis with Redisson (Java) DESCRIPTION: This Java code snippet demonstrates how to initialize the Redisson client to connect to an Upstash Redis database. It configures the connection using a password and endpoint (supporting SSL with rediss://), obtains a distributed map (RMap), puts a key-value pair, and then retrieves and prints the value. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/redisson.mdx#_snippet_1 LANGUAGE: Java CODE: ``` public class Main { public static void main(String[] args) { Config config = new Config(); config.useSingleServer().setPassword("YOUR_PASSWORD") // use "rediss://" for SSL connection .setAddress("YOUR_ENDPOINT"); RedissonClient redisson = Redisson.create(config); RMap map = redisson.getMap("map"); map.put("foo", "bar"); System.out.println(map.get("foo")); } } ``` ---------------------------------------- TITLE: Setting up SRH and Redis via Docker Compose DESCRIPTION: This Docker Compose configuration defines two services: a standard Redis server and the Serverless Redis HTTP (SRH) container. It sets up port mappings for both services and configures SRH using environment variables to connect to the Redis service within the same Docker network using its service name as the hostname. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/developing.mdx#_snippet_1 LANGUAGE: yaml CODE: ``` version: "3" services: redis: image: redis ports: - "6379:6379" serverless-redis-http: ports: - "8079:80" image: hiett/serverless-redis-http:latest environment: SRH_MODE: env SRH_TOKEN: example_token SRH_CONNECTION_STRING: "redis://redis:6379" # Using `redis` hostname since they're in the same Docker network. ``` ---------------------------------------- TITLE: Implementing Caching in Todo Controller in Laravel PHP DESCRIPTION: Shows a Laravel controller (`TodoController`) implementing caching logic for CRUD operations on Todo items using `Illuminate\Support\Facades\Cache`. It defines cache keys and TTLs, uses `Cache::flexible` for reading data with a fallback to the database, and invalidates relevant cache entries (`Cache::forget`) after create, update, or delete operations. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/laravel_caching.mdx#_snippet_17 LANGUAGE: php CODE: ``` validate([ 'title' => 'required|string|max:255', ]); $todo = Todo::create($request->all()); // Invalidate the todos cache Cache::forget(self::CACHE_KEY); return response()->json($todo, Response::HTTP_CREATED); } /** * Display the specified resource. */ public function show(Todo $todo): Todo { return Cache::flexible( "todo.{$todo->id}", self::CACHE_TTL, function () use ($todo) { return $todo; } ); } /** * Update the specified resource in storage. */ public function update(Request $request, Todo $todo): JsonResponse { $request->validate([ 'title' => 'required|string|max:255', ]); $todo->update($request->all()); // Invalidate both the collection and individual todo cache Cache::forget(self::CACHE_KEY); Cache::forget("todo.{$todo->id}"); return response()->json($todo); } /** * Remove the specified resource from storage. */ public function destroy(Todo $todo): JsonResponse { $todo->delete(); // Invalidate both the collection and individual todo cache Cache::forget(self::CACHE_KEY); Cache::forget("todo.{$todo->id}"); return response()->json(null, Response::HTTP_NO_CONTENT); } } ``` ---------------------------------------- TITLE: Executing Redis Transaction TypeScript DESCRIPTION: Illustrates how to create a Redis transaction using `redis.multi()`, enqueue multiple commands (`set`, `get`), and execute them atomically with `await tx.exec()`. Transactions ensure that all commands are executed together as a single operation or none are, preventing interleaving commands from other clients. It returns an array of results if the transaction completes successfully. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/transaction.mdx#_snippet_1 LANGUAGE: typescript CODE: ``` const tx = redis.multi(); tx.set("foo", "bar"); tx.get("foo"); const res = await tx.exec(); ``` ---------------------------------------- TITLE: Fetching Weather Data from Redis Cache with Redix in Elixir DESCRIPTION: This private Elixir function attempts to fetch weather data from the Redis cache using the Redix client. It constructs a Redis key based on the location ('weather:location') and executes a `GET` command. If the key is not found (returns `nil`), it returns `{:error, :not_found}`; otherwise, it decodes the JSON string using Jason and returns the parsed map. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/elixir.mdx#_snippet_11 LANGUAGE: Elixir CODE: ``` defp fetch_weather_from_cache(location) do case Redix.command(:redix, ["GET", "weather:#{location}"]) do {:ok, nil} -> {:error, :not_found} {:ok, cached_weather_json} -> {:ok, Jason.decode!(cached_weather_json)} {:error, _reason} -> {:error, "Failed to fetch weather data from cache."} end end ``` ---------------------------------------- TITLE: Getting Score of Member in Redis Sorted Set - Python DESCRIPTION: This Python snippet demonstrates how to use a Redis client library (like redis-py) to add members to a sorted set using `zadd` and then retrieve the score of a specific member using `zscore`. It adds members 'a', 'b', and 'c' with scores 1, 2, and 3 respectively to the 'myset' sorted set, and then asserts that the score of 'a' is 1. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zscore.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zscore("myset", "a") == 1 ``` ---------------------------------------- TITLE: Fetching Weather Data from External API and Caching with Redix in Elixir DESCRIPTION: This private Elixir function fetches weather data from the WeatherAPI using HTTPoison. It constructs the API URL using a `WEATHER_API_KEY` from system environment variables and the location. Upon a successful HTTP 200 response, it processes the JSON body, extracts relevant weather information using `get_weather_info`, caches the result in Redis using `cache_weather_response`, and returns the extracted information. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/elixir.mdx#_snippet_12 LANGUAGE: Elixir CODE: ``` defp fetch_weather_from_api(location) do weather_api_key = System.get_env("WEATHER_API_KEY") url = "http://api.weatherapi.com/v1/current.json?key=#{weather_api_key}&q=#{location}&aqi=no" case HTTPoison.get(url) do {:ok, %{status_code: 200, body: body}} -> weather_info = body |> Jason.decode!() |> get_weather_info() # Cache the weather response in Redis for 8 hours cache_weather_response(location, Jason.encode!(weather_info)) {:ok, weather_info} {:ok, %{status_code: status_code, body: body}} -> {:error, "#{body} (#{status_code})"} {:error, _reason} -> {:error, "Failed to fetch weather data."} end end ``` ---------------------------------------- TITLE: Implementing Cloud Function Logic with Upstash Redis in Javascript DESCRIPTION: This snippet initializes the Upstash Redis client using URL and token from environment variables. It defines an HTTP Cloud Function named `counter` that asynchronously increments a Redis key also named `counter` and returns the new value in the response. Dependencies: `@upstash/redis`, `@google-cloud/functions-framework`. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/using_google_cloud_functions.mdx#_snippet_0 LANGUAGE: javascript CODE: ``` const { Redis } = require("@upstash/redis"); const functions = require('@google-cloud/functions-framework'); const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN }); functions.http('counter', async (req, res) => { const count = await redis.incr("counter"); res.send("Counter:" + count); }); ``` ---------------------------------------- TITLE: Handling API Request with Upstash Redis - TypeScript DESCRIPTION: TypeScript code for a Next.js Pages Router API route located at `/pages/api/hello.ts`. It initializes the Upstash Redis client using environment variables, increments a key named 'counter' in the database upon each request, and responds with the new value of the counter as a JSON object. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/vercel-functions-pages-router.mdx#_snippet_2 LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis"; import type { NextApiRequest, NextApiResponse } from "next"; const redis = Redis.fromEnv(); export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { const count = await redis.incr("counter"); res.status(200).json({ count }); } ``` ---------------------------------------- TITLE: Fetching Location-Based Greeting from Redis in Cloudflare Worker DESCRIPTION: Provides the Javascript code for a Cloudflare Worker that uses the `@upstash/redis/cloudflare` library. It retrieves the client's country from the `cf-ipcountry` header, fetches the corresponding greeting from Redis, and returns it as an HTTP response, falling back to a default greeting if needed. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/getstartedcloudflareworkers.mdx#_snippet_2 LANGUAGE: javascript CODE: ``` // src/index.js import { Redis } from "@upstash/redis/cloudflare"; export default { async fetch(request, env) { const redis = Redis.fromEnv(env); const country = request.headers.get("cf-ipcountry"); if (country) { const greeting = await redis.get(country); if (greeting) { return new Response(greeting); } } return new Response("Hello!"); }, }; ``` ---------------------------------------- TITLE: Implementing Rate-Limited AWS Lambda Handler (JavaScript) DESCRIPTION: This JavaScript code defines the AWS Lambda handler function. It initializes the Upstash Ratelimit client using connection details from environment variables, applies a sliding window rate limit based on the client's source IP, and returns a 429 status code if the limit is exceeded, otherwise 200. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/rate-limiting.mdx#_snippet_5 LANGUAGE: javascript CODE: ``` const { Ratelimit } = require("@upstash/ratelimit"); const { Redis } = require("@upstash/redis"); const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), prefix: "@upstash/ratelimit", analytics: true, }); exports.ratelimit = async (event) => { const identifier = event.requestContext.http.sourceIP; const { success, limit, remaining, pending } = await ratelimit.limit( identifier ); const response = { success: success, limit: limit, remaining: remaining, }; // pending is a promise for handling the analytics submission await pending; if (!success) { return { statusCode: 429, body: JSON.stringify(response), }; } return { statusCode: 200, body: JSON.stringify(response), }; }; ``` ---------------------------------------- TITLE: Popping Multiple Members with Count - Upstash Redis TypeScript DESCRIPTION: This snippet shows how to add members to a Redis set and then use SPOP with the optional count argument set to 2 to remove and return multiple random members from the set. It logs the array of members that were popped. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/spop.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.sadd("set", "a", "b", "c"); const popped = await redis.spop("set", 2); console.log(popped); // ["a", "b"] ``` ---------------------------------------- TITLE: Demonstrating Per-Query Caching - TypeScript DESCRIPTION: Shows how to use per-query caching by explicitly calling `.$withCache()` on a query. An `insert` operation is shown first (which typically invalidates relevant cache entries), followed by a `select` query that is configured to read from the cache using `.$withCache()`. This is the default behavior when `global` is not set to `true`. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/drizzle.mdx#_snippet_3 LANGUAGE: typescript CODE: ``` await db.insert(users).value({ email: "cacheman@upstash.com" }); // 👇 reads from cache await db.select().from(users).$withCache() ``` ---------------------------------------- TITLE: Creating a FastAPI Application with Upstash Redis (Python) DESCRIPTION: This Python code defines a basic FastAPI application. It initializes the `FastAPI` app, connects to Upstash Redis using credentials from environment variables (`Redis.from_env()`), and creates a root endpoint (`/`) that increments a Redis counter key and returns its current value. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/fastapi.mdx#_snippet_2 LANGUAGE: python CODE: ``` from fastapi import FastAPI from upstash_redis import Redis app = FastAPI() redis = Redis.from_env() @app.get("/") def read_root(): count = redis.incr('counter') return {"count": count} ``` ---------------------------------------- TITLE: Implementing Counter Logic in Next.js Home Page DESCRIPTION: This code snippet for /app/page.tsx demonstrates how to initialize the @upstash/redis client using environment variables and perform a simple increment operation on a key named "counter". It then renders the current value of the counter on the page. This shows a basic read/write operation using Redis in a server component context. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/nextjs-app-router.mdx#_snippet_2 LANGUAGE: tsx CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ``` ---------------------------------------- TITLE: Implementing Lambda Counter Function with Upstash Redis (Python) DESCRIPTION: This Python code defines the AWS Lambda handler function (`lambda_handler`) for the counter application. It initializes an Upstash Redis client using connection details from environment variables, increments a key named 'counter' in Redis, and returns the updated count in the HTTP response body. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/using_aws_sam.mdx#_snippet_3 LANGUAGE: python CODE: ``` from upstash_redis import Redis redis = Redis.from_env() def lambda_handler(event, context): count = redis.incr('counter') return { 'statusCode': 200, 'body': f'Counter: {count}' } ``` ---------------------------------------- TITLE: Configuring Serverless Service (YAML) DESCRIPTION: Configures the Serverless service, specifying the AWS provider, Node.js 20.x runtime, and passing the Upstash Redis environment variables to the function. It defines the `counter` function, links it to the `handler.counter` code, and exposes it via an HTTP GET endpoint at the root path. Requires the `.env` file for variable resolution. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/using_serverless_framework.mdx#_snippet_7 LANGUAGE: yaml CODE: ``` service: counter-serverless provider: name: aws runtime: nodejs20.x environment: UPSTASH_REDIS_REST_URL: ${env:UPSTASH_REDIS_REST_URL} UPSTASH_REDIS_REST_TOKEN: ${env:UPSTASH_REDIS_REST_TOKEN} functions: counter: handler: handler.counter events: - httpApi: path: / method: get ``` ---------------------------------------- TITLE: Defining AWS CDK Stack (TypeScript) DESCRIPTION: Defines the AWS CDK stack (`CounterCdkStack`) that provisions the Lambda function. It uses `aws-cdk-lib/aws-lambda-nodejs` to bundle the function code, sets the Node.js 20.x runtime, passes Upstash Redis environment variables, and adds a public Function URL endpoint. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/api_with_cdk.mdx#_snippet_4 LANGUAGE: TypeScript CODE: ``` import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as nodejs from 'aws-cdk-lib/aws-lambda-nodejs'; export class CounterCdkStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const counterFunction = new nodejs.NodejsFunction(this, 'CounterFunction', { entry: 'api/counter.ts', handler: 'handler', runtime: lambda.Runtime.NODEJS_20_X, environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || '', UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || '', }, bundling: { format: nodejs.OutputFormat.ESM, target: "node20", nodeModules: ['@upstash/redis'], }, }); const counterFunctionUrl = counterFunction.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, }); new cdk.CfnOutput(this, "counterFunctionUrlOutput", { value: counterFunctionUrl.url, }) } } ``` ---------------------------------------- TITLE: Implementing Redis pipelining in Python DESCRIPTION: Illustrates how to create a Redis pipeline using `redis.pipeline()` to batch multiple commands for efficient execution in a single round trip. The commands are added to the pipeline and then executed using `exec()`, returning a list of results. Requires an initialized `redis` client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/features.mdx#_snippet_2 LANGUAGE: python CODE: ``` pipeline = redis.pipeline() pipeline.set("foo", 1) pipeline.incr("foo") pipeline.get("foo") result = pipeline.exec() print(result) # prints [True, 2, '2'] ``` ---------------------------------------- TITLE: Retrieving Value with Upstash Redis (TypeScript) DESCRIPTION: Demonstrates fetching a key's value using the Upstash Redis client in TypeScript. It shows how to specify the expected type using generics and handle the case where the key does not exist by checking for a null return value. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/get.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` type MyType = { a: number; b: string; } const value = await redis.get("key"); if (!value) { // key doesn't exist } else { // value is of type MyType } ``` ---------------------------------------- TITLE: Adding/Updating Sorted Set Members with ZADD - Python DESCRIPTION: Demonstrates various uses of the Redis ZADD command in Python, including adding multiple members, using 'nx' to prevent updates, using 'xx' to prevent adds, and using 'gt' for conditional updates based on score comparison. Requires a connected Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zadd.mdx#_snippet_0 LANGUAGE: Python CODE: ``` # Add three elements assert redis.zadd("myset", { "one": 1, "two": 2, "three": 3 }) == 3 # No element is added since "one" and "two" already exist assert redis.zadd("myset", { "one": 1, "two": 2 }, nx=True) == 0 # New element is not added since it does not exist assert redis.zadd("myset", { "new-element": 1 }, xx=True) == 0 # Only "three" is updated since new score was greater assert redis.zadd("myset", { "three": 10, "two": 0 }, gt=True) == 1 # Only "three" is updated since new score was greater assert redis.zadd("myset", { "three": 10, "two": 0 }, gt=True) == 1 ``` ---------------------------------------- TITLE: Querying Sorted Set Range in Python DESCRIPTION: Demonstrates fetching a range of elements from a Redis sorted set by index using the ZRANGE command. Requires an initialized Redis client and a sorted set with data. It adds elements and then asserts the range [0, 1] returns expected values. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zrange.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrange("myset", 0, 1) == ["a", "b"] ``` ---------------------------------------- TITLE: Using LPUSH with Upstash Redis in Python DESCRIPTION: This snippet demonstrates how to use the `LPUSH` command with a Redis client in Python to push multiple elements onto a list. It then uses the `LRANGE` command to retrieve the list and asserts the expected outcome: the new list length and the order of elements (last pushed elements are at the head). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/lpush.mdx#_snippet_0 LANGUAGE: Python CODE: ``` assert redis.lpush("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["three", "two", "one"] ``` ---------------------------------------- TITLE: Incrementing float value in Redis with TypeScript DESCRIPTION: This snippet demonstrates how to use a Redis client (likely Upstash Redis) to set an initial value for a key and then increment its float value using the INCRBYFLOAT command. It requires a Redis client instance named `redis`. The example sets the key 'key' to 6, then increments it by 4.5, showing the resulting value 10.5. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/incrbyfloat.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.set("key", 6); await redis.incrbyfloat("key", 4,5); // returns 10.5 ``` ---------------------------------------- TITLE: Creating Upstash Redis Client - TypeScript/JavaScript DESCRIPTION: Shows how to initialize the @upstash/redis client using Redis.fromEnv(), which automatically reads connection details from environment variables populated by the Vercel integration. It then demonstrates basic set and get operations and returns the result in a JSON response. Requires the @upstash/redis package. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/vercelintegration.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` const { Redis } = require("@upstash/redis"); module.exports = async (req, res) => { /** * Redis.fromEnv() will read the following from environment variables: * - UPSTASH_REDIS_REST_URL * - UPSTASH_REDIS_REST_TOKEN */ const redis = Redis.fromEnv(); await redis.set("foo", "bar"); const bar = await redis.get("foo"); res.json({ body: `foo: ${bar}`, }); }; ``` ---------------------------------------- TITLE: Implement Flask SocketIO Server with Redis Message Queue DESCRIPTION: Sets up a Flask application integrated with Flask-SocketIO. It configures the SocketIO instance to use Upstash Redis via the 'rediss://' URL for secure, real-time message broadcasting. Includes handlers for client connection, disconnection, and incoming messages, broadcasting received messages to other clients. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_realtime_chat.mdx#_snippet_2 LANGUAGE: python CODE: ``` from flask import Flask, render_template from flask_socketio import SocketIO import os # Initialize Flask app app = Flask(__name__) app.config["SECRET_KEY"] = os.getenv("SECRET_KEY", os.urandom(24)) # Set up Redis URL with TLS redis_password = os.getenv('UPSTASH_REDIS_PASSWORD') redis_host = os.getenv('UPSTASH_REDIS_HOST') redis_port = int(os.getenv('UPSTASH_REDIS_PORT', 6379)) redis_url = f"rediss://:{redis_password}@{redis_host}:{redis_port}" # Initialize SocketIO with Redis message queue socketio = SocketIO(app, message_queue=redis_url, cors_allowed_origins="*") # WebSocket handlers @socketio.on("connect") def handle_connect(): print("Client connected.") @socketio.on("disconnect") def handle_disconnect(): print("Client disconnected.") @socketio.on("message") def handle_message(data): """Handle incoming chat messages.""" print(f"Message received: {data}") # Broadcast the message to all connected clients except the sender socketio.emit("message", data, include_self=False) # Serve the chat HTML page @app.route("/") def index(): return render_template("chat.html") # Render the chat interface template if __name__ == "__main__": socketio.run(app, debug=True, host="0.0.0.0", port=8000) ``` ---------------------------------------- TITLE: Implementing AWS Lambda Redis Handler (Node.js) DESCRIPTION: Node.js AWS Lambda handler function that connects to an Upstash Redis database using ioredis, sets a key-value pair ('foo' to 'bar'), and then retrieves the value of 'foo'. The connection is cached outside the handler to potentially improve performance on warm starts. The result is returned in an HTTP response format. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/getstartedawslambda.mdx#_snippet_2 LANGUAGE: javascript CODE: ``` var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); } exports.handler = async (event) => { await client.set("foo", "bar"); let result = await client.get("foo"); let response = { statusCode: 200, body: JSON.stringify({ result: result, }), }; return response; }; ``` ---------------------------------------- TITLE: Creating API Route - Upstash Redis - TypeScript DESCRIPTION: This snippet defines a Next.js App Router API route handler (`/app/api/hello/route.ts`). It initializes the Upstash Redis client using environment variables and defines a GET request handler that increments a counter in Redis and returns the new value as a JSON response. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/vercel-functions-app-router.mdx#_snippet_2 LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis"; import { NextResponse } from "next/server"; const redis = Redis.fromEnv(); export async function GET() { const count = await redis.incr("counter"); return NextResponse.json({ count }); } export const dynamic = 'force-dynamic' ``` ---------------------------------------- TITLE: Setting Single Field in Redis Hash (Python) DESCRIPTION: This Python snippet demonstrates how to set a single field and its value in a Redis hash using the `redis.hset()` method. It takes the hash key ('myhash'), the field name ('field1'), and the value ('Hello') as arguments and asserts that the method returns 1, indicating one field was added or updated. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hset.mdx#_snippet_0 LANGUAGE: python CODE: ``` # Set a single field assert redis.hset("myhash", "field1", "Hello") == 1 ``` ---------------------------------------- TITLE: Calling Ratelimit Limit Method with Protection (TSX) DESCRIPTION: This TypeScript/TSX snippet demonstrates calling the `limit` method on an initialized Ratelimit client, providing an identifier and optional context like IP, user agent, and country. It shows how to destructure the result to get the denial status, reason, and the denied value, emphasizing the importance of awaiting the `pending` promise for background tasks like analytics or auto-update to complete. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/traffic-protection.mdx#_snippet_1 LANGUAGE: tsx CODE: ``` const { success, pending, reason, deniedValue } = ratelimit.limit("userId", { ip: "ip-address", userAgent: "user-agent", country: "country", }); await pending; // await pending if you have analytics enabled console.log(success, reason, deniedValue); // prints: false, "denyList", "ip-address" ``` ---------------------------------------- TITLE: Retrieving JSON Value from Redis (TypeScript) DESCRIPTION: Retrieves a value from a JSON document stored in Redis at the specified key and path using the `redis.json.get` method. Requires a connected Redis client instance (e.g., from Upstash or ioredis). Takes the Redis key and one or more JSON paths as arguments. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/get.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const value = await redis.json.get("key", "$.path.to.somewhere"); ``` ---------------------------------------- TITLE: Implementing Sidekiq Worker and Job Scheduling in Ruby DESCRIPTION: This Ruby code defines a Sidekiq worker class (`EmailService`), configures Sidekiq to connect to Upstash Redis using an environment variable, and provides helper functions (`updateEmail`, `sendEmail`, `clearSchedules`) to enqueue jobs asynchronously, schedule jobs with delays, manage scheduled jobs by ID, and clear queues. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/sidekiq.mdx#_snippet_1 LANGUAGE: ruby CODE: ``` require "sidekiq" require "sidekiq/api" connection_url = ENV['UPSTASH_REDIS_LINK'] Sidekiq.configure_client do |config| config.redis = {url: connection_url} end Sidekiq.configure_server do |config| config.redis = {url: connection_url} end class EmailService include Sidekiq::Worker def perform(id, type) # Logic goes here. Let's assume sending email by printing to console. puts "Emailed to: " + id + ": " + "'Congrats on " + type + " plan.'" end end def updateEmail(id, newType) jobFound = false a = Sidekiq::ScheduledSet.new a.each do |job| if job.args[0] == id job.delete jobFound = true end end if jobFound EmailService.perform_async(id, ("starting using our service and upgrading it to " + newType)) else EmailService.perform_async(id, ("upgrading to " + newType)) end end def sendEmail(id, type) case type when "free" # if free, delay for 10 seconds. EmailService.perform_in("10", id, "free") when "paid" # if paid, delay for 5 seconds. EmailService.perform_in("5", id, "paid") when "enterprise" # if enterprise, immediately queue. EmailService.perform_async(id, "enterprise") when "enterprise10k" EmailService.perform_async(id, "enterprise10k") else puts "Only plans are: `free`, `paid` and `enterprise`" end end def clearSchedules() Sidekiq::ScheduledSet.new.clear Sidekiq::Queue.new.clear end ``` ---------------------------------------- TITLE: Exporting Upstash Redis Environment Variables Shell DESCRIPTION: Sets the environment variables required for the Upstash Redis client to connect to your database. `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` must be replaced with your actual credentials obtained from the Upstash Console or CLI. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_fastapi_caching.mdx#_snippet_1 LANGUAGE: Shell CODE: ``` export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Configuring Upstash Redis Credentials (.env/Shell) DESCRIPTION: Defines the standard environment variables `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` within a `.env` file to provide connection details for the Upstash Redis database. Replace placeholders with actual credentials from your Upstash console. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/nextjs_with_redis.mdx#_snippet_1 LANGUAGE: Shell CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Sharing Read Your Writes Sync Token Between Clients (TypeScript) DESCRIPTION: Shows how to explicitly pass the `readYourWritesSyncToken` obtained from a client instance after a write operation to a *different* client instance before it performs a read. This ensures the second client syncs to the primary's state reflected by the token, preventing stale reads and maintaining consistency across client instances. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/readyourwrites.mdx#_snippet_1 LANGUAGE: TypeScript CODE: ``` export const writeRequest = async () => { const redis = Redis.fromEnv(); const randomKey = nanoid(); await redis.set(randomKey, "value"); // Get the token **after** making the write const token = redis.readYourWritesSyncToken; return { randomKey, token }; }; export const readRequest = async ( randomKey: string, token: string | undefined ) => { const redis = Redis.fromEnv(); // Set the token **before** making the read redis.readYourWritesSyncToken = token; const value = await redis.get(randomKey); return value; }; ``` ---------------------------------------- TITLE: Adding Multiple Members to Sorted Set (TypeScript) DESCRIPTION: Demonstrates adding multiple members with their scores to a sorted set using the ZADD command in TypeScript. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zadd.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.zadd( "key", { score: 2, member: "member" }, { score: 3, member: "member2"}, ); ``` ---------------------------------------- TITLE: Fetching Feature List from Redis in Next.js API DESCRIPTION: This Next.js API route (`/api/list`) connects to an Upstash Serverless Redis database using `ioredis`. It fetches feature requests and their associated vote counts from the Redis Sorted Set named "roadmap" using the `ZREVRANGE` command, ordering them by score in descending order. The results are then formatted into an array of objects (title and score) and returned as a JSON response. It requires a `REDIS_URL` environment variable and the `fixUrl` utility function. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/roadmapvotingapp.mdx#_snippet_1 LANGUAGE: javascript CODE: ``` import { fixUrl } from "./utils"; import Redis from "ioredis"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); let n = await redis.zrevrange("roadmap", 0, 100, "WITHSCORES"); let result = []; for (let i = 0; i < n.length - 1; i += 2) { let item = {}; item["title"] = n[i]; item["score"] = n[i + 1]; result.push(item); } redis.quit(); res.json({ body: result, }); }; ``` ---------------------------------------- TITLE: Configuring Different Ratelimit Strategies for Multiple Routes - JSON DESCRIPTION: This JSON snippet demonstrates configuring the Upstash Ratelimit Strapi plugin to apply different rate limiting strategies to specific routes. It sets a fixed-window limit for GET/POST on `/api/restaurants/:id` and a token-bucket limit for GET on `/api/restaurants`, both using the `x-author` header for identification. Proper plugin installation and Upstash Redis credentials are required. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/ratelimit/strapi/configurations.mdx#_snippet_2 LANGUAGE: json CODE: ``` { "strapi-plugin-upstash-ratelimit": { "enabled": true, "resolve": "./src/plugins/strapi-plugin-upstash-ratelimit", "config": { "enabled": true, "token": "process.env.UPSTASH_REDIS_REST_TOKEN", "url": "process.env.UPSTASH_REDIS_REST_URL", "strategy": [ { "methods": ["GET", "POST"], "path": "/api/restaurants/:id", "identifierSource": "header.x-author", "limiter": { "algorithm": "fixed-window", "tokens": 10, "window": "20s" } }, { "methods": ["GET"], "path": "/api/restaurants", "identifierSource": "header.x-author", "limiter": { "algorithm": "tokenBucket", "tokens": 10, "window": "20s", "refillRate": 1 } } ], "prefix": "@strapi" } } } ``` ---------------------------------------- TITLE: Adding Members to a Redis Set with Upstash Client in TypeScript DESCRIPTION: This snippet demonstrates how to add members to a Redis Set using the Upstash Redis client's `sadd` command in TypeScript. It shows two examples: one adding unique members (resulting in a return value equal to the number of members added) and another attempting to add members, some of which already exist (resulting in a return value only for the newly added, unique members). The command requires the set `key` and one or more `members` to add. The response is the number of elements actually added to the set. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/sadd.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` // 3 await redis.sadd("key", "a", "b", "c"); ``` LANGUAGE: typescript CODE: ``` // 0 await redis.sadd("key", "a", "b"); ``` ---------------------------------------- TITLE: Initialize and Use Upstash Ratelimit Client DESCRIPTION: Demonstrates how to initialize a new `Ratelimit` instance using an Upstash Redis client obtained from environment variables and perform a rate limit check against an identifier. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/gettingstarted.mdx#_snippet_1 LANGUAGE: ts CODE: ``` import { Ratelimit } from "@upstash/ratelimit"; // for deno: see above import { Redis } from "@upstash/redis"; // Create a new ratelimiter, that allows 10 requests per 10 seconds const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), analytics: true, /** * Optional prefix for the keys used in redis. This is useful if you want to share a redis * instance with other applications and want to avoid key collisions. The default prefix is * "@upstash/ratelimit" */ prefix: "@upstash/ratelimit", }); // Use a constant string to limit all requests with a single ratelimit // Or use a userID, apiKey or ip address for individual limits. const identifier = "api"; const { success } = await ratelimit.limit(identifier); if (!success) { return "Unable to process at this time"; } doExpensiveCalculation(); return "Here you go!"; ``` ---------------------------------------- TITLE: Implementing Multithreaded Web Scraper with Redis Caching DESCRIPTION: Provides the complete Python code for the web scraper. It defines a `Scraper` class inheriting from `threading.Thread`, initializes the Redis client using environment variables, groups URLs for threads, implements the caching logic (check cache, fetch if miss, cache response), and manages thread execution. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_multithreading.mdx#_snippet_2 LANGUAGE: python CODE: ``` import threading import requests from upstash_redis import Redis from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Initialize Redis client redis = Redis.from_env() # Group URLs by thread, with one or two overlapping URLs across groups urls_to_scrape_groups = [ [ 'https://httpbin.org/delay/1', 'https://httpbin.org/delay/4', 'https://httpbin.org/delay/2', 'https://httpbin.org/delay/5', 'https://httpbin.org/delay/3', ], [ 'https://httpbin.org/delay/5', # Overlapping URL 'https://httpbin.org/delay/6', 'https://httpbin.org/delay/7', 'https://httpbin.org/delay/2', # Overlapping URL 'https://httpbin.org/delay/8', ], [ 'https://httpbin.org/delay/3', # Overlapping URL 'https://httpbin.org/delay/9', 'https://httpbin.org/delay/10', 'https://httpbin.org/delay/4', # Overlapping URL 'https://httpbin.org/delay/11', ], ] class Scraper(threading.Thread): def __init__(self, urls): threading.Thread.__init__(self) self.urls = urls self.results = {} def run(self): for url in self.urls: cache_key = f"url:{url}" # Attempt to retrieve cached response cached_response = redis.get(cache_key) if cached_response: print(f"[CACHE HIT] {self.name} - URL: {url}") self.results[url] = cached_response continue # Skip to the next URL if cache is found # If no cache, perform the HTTP request print(f"[FETCHING] {self.name} - URL: {url}") response = requests.get(url) if response.status_code == 200: self.results[url] = response.text # Store the response in Redis cache redis.set(cache_key, response.text) else: print(f"[ERROR] {self.name} - Failed to retrieve {url}") self.results[url] = None def main(): threads = [] for urls in urls_to_scrape_groups: scraper = Scraper(urls) threads.append(scraper) scraper.start() # Wait for all threads to complete for scraper in threads: scraper.join() print("\nScraping results:") for scraper in threads: for url, result in scraper.results.items(): print(f"Thread {scraper.name} - URL: {url} - Response Length: {len(result) if result else 'Failed'}") if __name__ == "__main__": main() ``` ---------------------------------------- TITLE: Caching Weather Data in Redis with Expiration using Redix in Elixir DESCRIPTION: This private Elixir function stores weather data in Redis using the Redix client. It executes a `SET` command with the key 'weather:location', the JSON string `weather_data`, and an expiration time (`EX`) of 8 hours (8 * 60 * 60 seconds). It returns `:ok` on success or an error tuple on failure. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/elixir.mdx#_snippet_13 LANGUAGE: Elixir CODE: ``` defp cache_weather_response(location, weather_data) do case Redix.command(:redix, ["SET", "weather:#{location}", weather_data, "EX", 8 * 60 * 60]) do {:ok, _} -> :ok {:error, _reason} -> {:error, "Failed to cache weather data."} end end ``` ---------------------------------------- TITLE: Redis ZUNION with Weights and Aggregation in Python DESCRIPTION: Shows how to apply weights to the scores of input sets before aggregation during a ZUNION operation. It uses 'withscores=True', 'aggregate="SUM"', and provides specific weights for each key in the union. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zunion.mdx#_snippet_2 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zunion(["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == [("a", 5)] ``` ---------------------------------------- TITLE: Initializing Upstash Redis Client with Auto-Pipelining (TypeScript) DESCRIPTION: Demonstrates how to create an instance of the @upstash/redis client with the enableAutoPipelining option set to true, using both the fromEnv helper and the direct constructor. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/pipelining/auto-pipeline.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv({ latencyLogging: false, enableAutoPipelining: true }); ``` LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis"; const redis = new Redis({ url: , token: , enableAutoPipelining: true }) ``` ---------------------------------------- TITLE: Simple Counter App Connecting to Redis (Node.js) DESCRIPTION: Provides the source code for a minimal Node.js application using Express and the `redis` client library. It connects to Redis via a URL from `process.env.REDIS_URL` and implements a simple counter incremented on each HTTP GET request to the root path. Uses `promisify` for async Redis operations. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/fly.mdx#_snippet_1 LANGUAGE: javascript CODE: ``` const express = require("express"); const redis = require("redis"); const { promisify } = require("util"); const app = express(); const client = redis.createClient(process.env.REDIS_URL); const getAsync = promisify(client.get).bind(client); const setAsync = promisify(client.set).bind(client); app.get("/", async (req, res) => { const value = await getAsync("counter"); await setAsync("counter", parseInt(value || 0) + 1); res.send(`Hello, visitor number ${value || 0}!`); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); ``` ---------------------------------------- TITLE: Add Members to Set - Redis Python DESCRIPTION: Demonstrates how to use the sadd command with the Python redis client to add multiple members ('a', 'b', 'c') to a set named 'key'. It asserts that exactly 3 new members were added to the set, which is the expected response from SADD. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/sadd.mdx#_snippet_0 LANGUAGE: Python CODE: ``` assert redis.sadd("key", "a", "b", "c") == 3 ``` ---------------------------------------- TITLE: Implementing Worker Logic to Fetch Greeting (TypeScript) DESCRIPTION: Defines the Cloudflare Worker's `fetch` handler. It initializes the `@upstash/redis` client using environment variables, extracts the client's country from the request headers, attempts to retrieve a greeting from Redis using the country code as the key, and returns the greeting or a default message. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/cloudflare_workers_with_redis.mdx#_snippet_3 LANGUAGE: typescript CODE: ``` import { Redis } from '@upstash/redis/cloudflare'; type RedisEnv = { UPSTASH_REDIS_REST_URL: string; UPSTASH_REDIS_REST_TOKEN: string; }; export default { async fetch(request: Request, env: RedisEnv) { const redis = Redis.fromEnv(env); const country = request.headers.get('cf-ipcountry'); if (country) { const greeting = await redis.get(country); if (greeting) { return new Response(greeting); } } return new Response('Hello!'); }, }; ``` ---------------------------------------- TITLE: Adding New Feature Request to Redis in Next.js API DESCRIPTION: This Next.js API route (`/api/create`) handles the submission of new feature requests. It connects to the Redis database using `ioredis` and attempts to add the provided feature title to the "roadmap" Sorted Set with an initial score of 1. It uses the `ZADD` command with the "NX" flag to ensure the entry is only added if the title doesn't already exist. Basic validation checks for an empty or overly long title are included, returning an error response if they fail. Requires a `REDIS_URL` and `fixUrl`. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/roadmapvotingapp.mdx#_snippet_2 LANGUAGE: javascript CODE: ``` import Redis from "ioredis"; import { fixUrl } from "./utils"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); const body = req.body; const title = body["title"]; if (!title) { redis.quit(); res.json({ error: "Feature can not be empty", }); } else if (title.length < 70) { await redis.zadd("roadmap", "NX", 1, title); redis.quit(); res.json({ body: "success", }); } else { redis.quit(); res.json({ error: "Max 70 characters please.", }); } }; ``` ---------------------------------------- TITLE: Creating Bull Queue Consumer Worker in JavaScript DESCRIPTION: This JavaScript code defines a Node.js application that serves as the consumer worker. It initializes a Bull queue connected to Upstash Redis using the same queue name and settings as the producer. It then sets up a 'process' handler that executes for each job pulled from the queue, logging the job data and marking the job as complete. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/job_processing.mdx#_snippet_3 LANGUAGE: JavaScript CODE: ``` var Queue = require("bull"); var settings = { stalledInterval: 300000, // How often check for stalled jobs (use 0 for never checking). guardInterval: 5000, // Poll interval for delayed jobs and added jobs. drainDelay: 300, // A timeout for when the queue is in drained state (empty waiting for jobs). }; var taskQueue = new Queue( "employee registration", { redis: { port: 32016, host: "us1-upward-ant-32016.upstash.io", password: "ake4ff120d6b4216df220736be7eab087", tls: {}, }, }, settings ); taskQueue .process(function (job, done) { console.log(job.data); // TODO process the new employee event done(); }) .catch((err) => { console.log(err); }); ``` ---------------------------------------- TITLE: Create Counter Lambda Function TypeScript DESCRIPTION: Defines an AWS Lambda function handler in TypeScript. It uses the `@upstash/redis` client to connect to a Redis instance using environment variables, increments a key named "counter", and returns the new count in a JSON response. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/aws-lambda.mdx#_snippet_3 LANGUAGE: typescript CODE: ``` import { Redis } from '@upstash/redis'; const redis = Redis.fromEnv(); export const handler = async function() { const count = await redis.incr("counter"); return { statusCode: 200, body: JSON.stringify('Counter: ' + count), }; }; ``` ---------------------------------------- TITLE: Incrementing Sorted Set Member Score with Upstash Redis Client (TypeScript) DESCRIPTION: This snippet demonstrates how to use the Upstash Redis client to add a member to a sorted set using 'zadd' and then increment its score using 'zincrby'. It shows the typical sequence of operations and logs the resulting score after the increment. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zincrby.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.zadd("key", 1, "member"); const value = await redis.zincrby("key", 2, "member"); console.log(value); // 3 ``` ---------------------------------------- TITLE: Configuring Celery with Upstash Redis Broker/Backend (python) DESCRIPTION: Configures a Celery application instance, setting the message broker and result backend URL to the Upstash Redis connection string. It retrieves connection details from environment variables and defines a simple `add` task decorated with `@celery_app.task`. Requires `celery`, `redis`, `dotenv`, and environment variables (`UPSTASH_REDIS_HOST`, `UPSTASH_REDIS_PORT`, `UPSTASH_REDIS_PASSWORD`). SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/celery.mdx#_snippet_3 LANGUAGE: python CODE: ``` import os from celery import Celery from dotenv import load_dotenv load_dotenv() # Configure Celery with Upstash Redis UPSTASH_REDIS_HOST = os.getenv("UPSTASH_REDIS_HOST") UPSTASH_REDIS_PORT = os.getenv("UPSTASH_REDIS_PORT") UPSTASH_REDIS_PASSWORD = os.getenv("UPSTASH_REDIS_PASSWORD") connection_link = f"rediss://:{UPSTASH_REDIS_PASSWORD}@{UPSTASH_REDIS_HOST}:{UPSTASH_REDIS_PORT}?ssl_cert_reqs=required" celery_app = Celery("tasks", broker=connection_link, backend=connection_link) @celery_app.task def add(x, y): return x + y ``` ---------------------------------------- TITLE: Implementing Simple HTTP Server with Redis Counter (JavaScript) DESCRIPTION: This Node.js code creates a simple HTTP server that increments a counter stored in Redis for each page view and returns the current count. It uses the `http` module to create the server and `ioredis` to connect to the Redis database, retrieving the connection URL from the `REDIS_URL` environment variable. Requests to '/favicon.ico' are ignored. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/aws_app_runner_with_redis.mdx#_snippet_2 LANGUAGE: javascript CODE: ``` var Redis = require("ioredis"); const http = require("http"); if (typeof client === "undefined") { var client = new Redis(process.env.REDIS_URL); } const requestListener = async function (req, res) { if (req.url !== "/favicon.ico") { let count = await client.incr("counter"); res.writeHead(200); res.end("Page view:" + count); } }; const server = http.createServer(requestListener); server.listen(8080); ``` ---------------------------------------- TITLE: Setting up Next.js App Router Project and Dependencies DESCRIPTION: This command sequence creates a new Next.js application using the latest version, navigates into the project directory, and installs the @upstash/redis package as a dependency. This is the initial setup required to start integrating Upstash Redis into the project. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/nextjs-app-router.mdx#_snippet_0 LANGUAGE: shell CODE: ``` npx create-next-app@latest cd my-app npm install @upstash/redis ``` ---------------------------------------- TITLE: Initializing Drizzle ORM with Upstash Cache Options - TypeScript DESCRIPTION: Configures Drizzle ORM with the `upstashCache` helper, explicitly providing connection credentials, enabling global caching (`global: true`), and setting default cache configuration (e.g., expiration time `ex: 60`). This allows fine-grained control over the cache behavior. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/drizzle.mdx#_snippet_2 LANGUAGE: typescript CODE: ``` import { upstashCache } from "drizzle-orm/cache/upstash" import { drizzle } from "drizzle-orm/..." const db = drizzle(process.env.DB_URL!, { cache: upstashCache({ // 👇 Redis credentials (optional — can also be pulled from env vars) url: "", token: "", // 👇 Enable caching for all queries (optional, default false) global: true, // 👇 Default cache behavior (optional) config: { ex: 60 }, }), }) ``` ---------------------------------------- TITLE: Initializing Fixed Window Ratelimiter with Upstash Ratelimit Python DESCRIPTION: This code snippet demonstrates how to initialize a Ratelimit object using the FixedWindow algorithm provided by `upstash-ratelimit`. It requires a connection to a Redis instance, obtained here using `upstash_redis.Redis.from_env()`, and configures the limiter with the maximum allowed requests per window and the window duration in seconds. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-py/algorithms.mdx#_snippet_0 LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), ) ``` ---------------------------------------- TITLE: Initializing Separate Upstash Redis Clients (TypeScript) DESCRIPTION: Demonstrates how separate functions, intended for different API endpoints or contexts, initialize independent Upstash Redis client instances. This setup highlights the potential for read inconsistency when a read occurs shortly after a write from a different client instance, as their sync tokens are not shared automatically. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/readyourwrites.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` export const writeRequest = async () => { const redis = Redis.fromEnv(); const randomKey = nanoid(); await redis.set(randomKey, "value"); return randomKey; }; export const readRequest = async (randomKey: string) => { const redis = Redis.fromEnv(); const value = await redis.get(randomKey); return value; }; ``` ---------------------------------------- TITLE: Setting a Key With Expiration TypeScript DESCRIPTION: Shows how to set a key using the Upstash Redis client and specify an expiration time using the `ex` option. The key "my-key" is set with a value and configured to expire after 60 seconds. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/set.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.set("my-key", {my: "value"}, { ex: 60 }); ``` ---------------------------------------- TITLE: Implementing Next.js API Route with Upstash Redis (TypeScript) DESCRIPTION: Creates a Next.js API route (`/api/hello`) that initializes an Upstash Redis client using the secrets provided via SST's `Config`. The route increments a counter key in Redis on every request and returns the updated count. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/sst-v2.mdx#_snippet_4 LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis"; import type { NextApiRequest, NextApiResponse } from "next"; import { Config } from "sst/node/config"; const redis = new Redis({ url: Config.UPSTASH_REDIS_REST_URL, token: Config.UPSTASH_REDIS_REST_TOKEN, }); export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { const count = await redis.incr("counter"); res.status(200).json({ count }); } ``` ---------------------------------------- TITLE: Setting Expiration PEXPIRE in TypeScript DESCRIPTION: This snippet demonstrates how to use the `pexpire` method of a Redis client in TypeScript to set a time-to-live (TTL) in milliseconds for a specific key. It takes the key name and the expiration time in milliseconds as arguments, such as setting a 1-minute (60,000 ms) timeout for `key`. The method returns `1` if the timeout was applied and `0` if the key did not exist. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/pexpire.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.pexpire(key, 60_000); // 1 minute ``` ---------------------------------------- TITLE: Initialize and Use Upstash Redis Client (From Environment) - TypeScript DESCRIPTION: Illustrates how to initialize the `upstash-redis` client using the `fromEnv()` static method. This method automatically loads the connection URL and token from the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables. It also includes a simple `get` operation example. Requires `@upstash/redis` installed and the environment variables set. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/connectwithupstashredis.mdx#_snippet_2 LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv()(async () => { try { const data = await redis.get("key"); console.log(data); } catch (error) { console.error(error); } })(); ``` ---------------------------------------- TITLE: Using SET and SETRANGE with Redis (TypeScript) DESCRIPTION: This snippet demonstrates how to use the Redis SETRANGE command. It first sets a key 'key' to 'helloworld', then uses SETRANGE to replace the substring starting at offset 5 with 'redis'. Finally, it prints the new length of the string value. Requires a Redis client connection. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/setrange.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.set("key", "helloworld") const length = await redis.setrange("key", 5, "redis"); console.log(length); // 10 // The value of "key" is now "helloredis" ``` ---------------------------------------- TITLE: Initializing Drizzle ORM with Basic Upstash Cache - TypeScript DESCRIPTION: Demonstrates how to initialize Drizzle ORM with the `upstashCache` helper using default settings. The `upstashCache()` function connects to Upstash Redis, typically using environment variables for credentials. This setup enables per-query opt-in caching by default. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/drizzle.mdx#_snippet_1 LANGUAGE: typescript CODE: ``` import { upstashCache } from "drizzle-orm/cache/upstash" import { drizzle } from "drizzle-orm/..." const db = drizzle(process.env.DB_URL!, { cache: upstashCache(), }) ``` ---------------------------------------- TITLE: Creating New Supabase Function - Shell DESCRIPTION: Uses the Supabase Command Line Interface (CLI) to create a new serverless function named 'upstash-redis-counter' within your Supabase project structure. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/supabase.mdx#_snippet_1 LANGUAGE: shell CODE: ``` supabase functions new upstash-redis-counter ``` ---------------------------------------- TITLE: Initializing and Using Upstash Ratelimit (Python) DESCRIPTION: Demonstrates how to initialize the Upstash ratelimit client using a Redis connection obtained from environment variables and a `FixedWindow` limiter allowing 10 requests per 10 seconds. It shows how to apply a limit to an identifier ('api') and check the boolean `allowed` flag in the response before proceeding with a potentially expensive operation. Requires `upstash-ratelimit` and `upstash-redis`. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-py/gettingstarted.mdx#_snippet_1 LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis # Create a new ratelimiter, that allows 10 requests per 10 seconds ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), # Optional prefix for the keys used in Redis. This is useful # if you want to share a Redis instance with other applications # and want to avoid key collisions. The default prefix is # "@upstash/ratelimit" prefix="@upstash/ratelimit", ) # Use a constant string to limit all requests with a single ratelimit # Or use a user ID, API key or IP address for individual limits. identifier = "api" response = ratelimit.limit(identifier) if not response.allowed: print("Unable to process at this time") else: do_expensive_calculation() print("Here you go!") ``` ---------------------------------------- TITLE: Demonstrating Redis EXISTS in Python DESCRIPTION: This Python code snippet demonstrates the usage of the Redis EXISTS command. It first sets two keys, then calls EXISTS with both keys and asserts the result is 2. It then deletes one key and calls EXISTS again with the same two keys, asserting the result is 1, showcasing how the command returns the count of existing keys. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/exists.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.set("key1", "Hello") redis.set("key2", "World") assert redis.exists("key1", "key2") == 2 redis.delete("key1") assert redis.exists("key1", "key2") == 1 ``` ---------------------------------------- TITLE: Adding User Email to Redis Set in Next.js API DESCRIPTION: This Next.js API route (`/api/addemail`) handles adding user emails for notifications. It connects to Redis using `ioredis` and validates the provided email using the internal `validateEmail` helper function. If the email is valid, it adds the email to the Redis Set named "emails" using the `SADD` command. Redis Sets automatically ensure the uniqueness of members. If the email is invalid, an error response is returned. Requires a `REDIS_URL` and `fixUrl`. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/roadmapvotingapp.mdx#_snippet_4 LANGUAGE: javascript CODE: ``` import Redis from "ioredis"; import { fixUrl } from "./utils"; module.exports = async (req, res) => { let redis = new Redis(fixUrl(process.env.REDIS_URL)); const body = req.body; const email = body["email"]; redis.on("error", function (err) { throw err; }); if (email && validateEmail(email)) { await redis.sadd("emails", email); redis.quit(); res.json({ body: "success", }); } else { redis.quit(); res.json({ error: "Invalid email", }); } }; function validateEmail(email) { const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } ``` ---------------------------------------- TITLE: Calling Ratelimit Limit for Auto IP Protection (TS) DESCRIPTION: This TypeScript snippet demonstrates calling the `limit` method, focusing on providing an IP address for the Auto IP Deny List feature. It highlights the use of `await pending` after the initial `limit` call to ensure that asynchronous background processes, such as the daily update of the IP deny list, complete before proceeding. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/traffic-protection.mdx#_snippet_3 LANGUAGE: ts CODE: ``` const { success, pending } = await ratelimit.limit( content, {ip: "ip-address"} ); await pending; ``` ---------------------------------------- TITLE: Running Cloudflare Worker Locally (Shell) DESCRIPTION: Provides the command to start the local development server for the Cloudflare Worker using the Wrangler CLI, allowing testing before deployment. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/cloudflare_workers_with_redis.mdx#_snippet_4 LANGUAGE: shell CODE: ``` npx wrangler dev ``` ---------------------------------------- TITLE: Demonstrating Separate Pipeline Calls per Await (TypeScript) DESCRIPTION: Shows that when using auto-pipelining, awaiting each individual Redis command separately will result in a distinct pipeline execution for every await statement, reducing the batching benefit. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/pipelining/auto-pipeline.mdx#_snippet_2 LANGUAGE: TypeScript CODE: ``` const foo = await redis.get("foo") // makes a PIPELINE call const bar = await redis.get("bar") // makes another PIPELINE call ``` ---------------------------------------- TITLE: Implementing Lambda Handler | Java DESCRIPTION: Provides the Java implementation for the AWS Lambda function. It connects to a specified Upstash Redis instance using Jedis, authenticates, increments a key named "counter", closes the connection, and returns the updated counter value in the HTTP response. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/serverless_java_redis.mdx#_snippet_5 LANGUAGE: java CODE: ``` package com.serverless; import java.util.Map; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import redis.clients.jedis.Jedis; public class Handler implements RequestHandler, ApiGatewayResponse> { @Override public ApiGatewayResponse handleRequest(Map input, Context context) { Jedis jedis = new Jedis("lasting-roughy-29092.upstash.io", 6379, true); jedis.auth("********"); Long value = jedis.incr("counter"); jedis.close(); String message = "Hello World, Count:" + value; return ApiGatewayResponse.builder() .setStatusCode(200) .setObjectBody(message) .build(); } } ``` ---------------------------------------- TITLE: Implementing Redis Counter in Next.js Page with TSX DESCRIPTION: Imports the Upstash Redis client, initializes it using environment variables, increments a key named 'counter' in the database, and displays the resulting count on the Next.js home page. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/ion.mdx#_snippet_5 LANGUAGE: tsx CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv(); export default async function Home() { const count = await redis.incr("counter"); return (

Counter: {count}

) } ``` ---------------------------------------- TITLE: Configuring Retries for Upstash Redis Client in TypeScript DESCRIPTION: This snippet demonstrates how to initialize the @upstash/redis client with a custom retry policy. It shows how to specify the maximum number of retries using the `retries` property and define a custom backoff delay function using the `backoff` property within the `retry` configuration object. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/retries.mdx#_snippet_0 LANGUAGE: ts CODE: ``` new Redis({ url: UPSTASH_REDIS_REST_URL, token: UPSTASH_REDIS_REST_TOKEN, retry: { retries: 5, backoff: (retryCount) => Math.exp(retryCount) * 50, }, }); ``` ---------------------------------------- TITLE: Setting Up SST Next.js Project (shell) DESCRIPTION: Initializes a new SST project using the standard Next.js template, navigates into the newly created project directory, and installs the project's dependencies. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/sst-v2.mdx#_snippet_0 LANGUAGE: shell CODE: ``` npx create-sst@latest --template standard/nextjs cd my-sst-app npm install ``` ---------------------------------------- TITLE: Initializing Serverless Project Interactively (Shell) DESCRIPTION: Guides the user through creating a new Serverless Framework project using an interactive CLI, selecting AWS Node.js HTTP API template and naming the project. Creates the initial project structure. Requires Serverless Framework CLI installed. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/using_serverless_framework.mdx#_snippet_1 LANGUAGE: shell CODE: ``` ➜ tutorials > ✗ serverless Serverless ϟ Framework Welcome to Serverless Framework V.4 Create a new project by selecting a Template to generate scaffolding for a specific use-case. ✔ Select A Template: · AWS / Node.js / HTTP API ✔ Name Your Project: · counter-serverless ✔ Template Downloaded ✔ Create Or Select An Existing App: · Create A New App ✔ Name Your New App: · counter-serverless Your new Service "counter-serverless" is ready. Here are next steps: • Open Service Directory: cd counter-serverless • Install Dependencies: npm install (or use another package manager) • Deploy Your Service: serverless deploy ``` ---------------------------------------- TITLE: Setting Key and EXPIRE using TypeScript/JavaScript DESCRIPTION: This code snippet demonstrates how to use a Redis client library (likely in TypeScript or JavaScript) to first set a value for a specific key ('mykey') and then apply the EXPIRE command to set a 10-second timeout on that same key. This causes the key to be automatically deleted after 10 seconds. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/expire.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.set("mykey", "Hello"); await redis.expire("mykey", 10); ``` ---------------------------------------- TITLE: Creating Upstash QStash Publish Client - TypeScript/JavaScript DESCRIPTION: Shows how to initialize the @upstash/qstash client using the QSTASH_TOKEN environment variable and demonstrates publishing a JSON payload to a target URL. This is used for sending messages to external HTTP endpoints. Requires the @upstash/qstash package. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/vercelintegration.mdx#_snippet_2 LANGUAGE: TypeScript CODE: ``` import { Client } from "@upstash/qstash"; const c = new Client({ token: process.env.QSTASH_TOKEN, }); const res = await c.publishJSON({ url: "https://my-api...", body: { hello: "world", }, }); ``` ---------------------------------------- TITLE: Using Redis PERSIST Command in Python DESCRIPTION: This snippet demonstrates how to use the `persist` command in a Python Redis client. It shows setting a key, setting an expiration time, verifying the Time-To-Live (TTL), calling `persist` to remove the expiration, and finally verifying that the TTL is -1, indicating the key will not expire. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/persist.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.set("key1", "Hello") redis.expire("key1", 10) assert redis.ttl("key1") == 10 redis.persist("key1") assert redis.ttl("key1") == -1 ``` ---------------------------------------- TITLE: Sending Multi-Exec Transaction Request (Shell) DESCRIPTION: Demonstrates the basic syntax for sending a transaction request to the Upstash Redis REST API's /multi-exec endpoint using curl. It includes setting the authorization header and providing the transaction commands as a 2D JSON array in the request body. SOURCE: https://github.com/upstash/docs/blob/main/redis/features/restapi.mdx#_snippet_0 LANGUAGE: shell CODE: ``` curl -X POST https://us1-merry-cat-32748.upstash.io/multi-exec \ -H "Authorization: Bearer $TOKEN" \ -d ' [ ["CMD_A", "arg0", "arg1", ..., "argN"], ["CMD_B", "arg0", "arg1", ..., "argM"], ... ] ' ``` ---------------------------------------- TITLE: Install Upstash Redis Python Library DESCRIPTION: Provides the command to install the official upstash-redis Python library using the pip package manager. This command fetches the latest version from PyPI and installs it into your current Python environment, making the library available for import and use. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/gettingstarted.mdx#_snippet_0 LANGUAGE: bash CODE: ``` pip install upstash-redis ``` ---------------------------------------- TITLE: Using Multiple Ratelimit Instances for Tiers (TypeScript) DESCRIPTION: Provides an example of setting up and using multiple Ratelimit instances, each with different configurations (e.g., limits, prefixes), to apply varying rate limits based on identifiers like user type (free vs. paid). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/features.mdx#_snippet_3 LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis"; import { Ratelimit } from "@upstash/ratelimit"; const redis = Redis.fromEnv(); const ratelimit = { free: new Ratelimit({ redis, analytics: true, prefix: "ratelimit:free", limiter: Ratelimit.slidingWindow(10, "10s"), }), paid: new Ratelimit({ redis, analytics: true, prefix: "ratelimit:paid", limiter: Ratelimit.slidingWindow(60, "10s"), }), }; await ratelimit.free.limit(ip); // or for a paid user you might have an email or userId available: await ratelimit.paid.limit(userId); ``` ---------------------------------------- TITLE: Initializing Serverless Project using Shell DESCRIPTION: This command initializes a new Serverless project. It prompts the user for project details like template (AWS Node.js) and project name ('producer'), creating the necessary directory structure and configuration file to set up the serverless function for the producer. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/job_processing.mdx#_snippet_0 LANGUAGE: Shell CODE: ``` ➜ serverless Serverless: No project detected. Do you want to create a new one? Yes Serverless: What do you want to make? AWS Node.js Serverless: What do you want to call this project? producer Project successfully created in 'producer' folder. You can monitor, troubleshoot, and test your new service with a free Serverless account. Serverless: Would you like to enable this? No You can run the “serverless” command again if you change your mind later. ``` ---------------------------------------- TITLE: Unlinking Keys (Array) - Upstash Redis (TypeScript) DESCRIPTION: Illustrates how to use the Upstash Redis client's `unlink` method with an array of keys. The array elements are passed as individual arguments to the method using the spread (`...`) syntax. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/unlink.mdx#_snippet_1 LANGUAGE: TypeScript CODE: ``` // in case you have an array of keys const keys = ["key1", "key2"]; await redis.unlink(...keys) ``` ---------------------------------------- TITLE: Unlinking Keys (Basic) - Upstash Redis (TypeScript) DESCRIPTION: Demonstrates the basic usage of the Upstash Redis client's `unlink` method to remove multiple keys by passing them directly as arguments. It removes the specified keys from the Redis database asynchronously. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/unlink.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.unlink("key1", "key2"); ``` ---------------------------------------- TITLE: Setting JSON Value with XX (TypeScript) DESCRIPTION: This snippet demonstrates using the redis.json.set command in TypeScript with the xx: true option. This option ensures that the value is set only if the specified key or path already exists. It requires the key, path, value, and the xx: true option object. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/set.mdx#_snippet_2 LANGUAGE: ts CODE: ``` const value = ... redis.json.set(key, "$.path", value, { xx:true }); ``` ---------------------------------------- TITLE: Setting and Retrieving Redis Hash Fields (Python) DESCRIPTION: This snippet demonstrates setting multiple fields in a Redis hash using `redis.hset` and subsequently retrieving all fields and their corresponding values using `redis.hgetall`. It includes an assertion to verify that `hgetall` returns the expected dictionary containing all previously set hash fields. Requires an initialized Redis client object. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hgetall.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hgetall("myhash") == {"field1": "Hello", "field2": "World"} ``` ---------------------------------------- TITLE: Adding Members and Querying Scores in Redis (TypeScript) DESCRIPTION: This snippet demonstrates how to use the `zadd` command to add members with scores to a Redis sorted set and then utilize the `zmscore` command to retrieve the scores of specified members. It includes a `console.log` to display the result. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zmscore.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, { score: 3, member: "m3" }, { score: 4, member: "m4" }, ) const scores = await redis.zmscore("key", ["m2", "m4"]) console.log(scores) // [2, 4] ``` ---------------------------------------- TITLE: Incrementing a Hash Field value in TypeScript DESCRIPTION: This snippet demonstrates how to use the `hincrby` command with Upstash Redis in TypeScript. It first initializes a hash field 'field' with a value using `hset`, then uses `hincrby` to increment the value by 2, and finally prints the resulting value. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hincrby.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.hset("key", { field: 20, }); const after = await redis.hincrby("key", "field", 2); console.log(after); // 22 ``` ---------------------------------------- TITLE: Using Upstash Redis Auto-Pipelining with Async Calls and Promise.all (TypeScript) DESCRIPTION: Illustrates the use of auto-pipelining with the @upstash/redis client. It shows how individual async calls and commands grouped within Promise.all are handled, demonstrating that await triggers pipeline execution while Promise.all batches commands efficiently. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/pipelining/auto-pipeline.mdx#_snippet_1 LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis"; const redis = Redis.fromEnv({ latencyLogging: false, enableAutoPipelining: true }); // async call to redis. Not executed right away, instead // added to the pipeline redis.hincrby("Brooklyn", "visited", 1); // making requests in batches const brooklynInfo = Promise.all([ redis.hget("Brooklyn", "coordinates"), redis.hget("Brooklyn", "population") ]); // when we call await, the three commands are executed // as a pipeline automatically. A single PIPELINE command // is executed instead of three requests and the results // are returned: const [ coordinates, population ] = await brooklynInfo; ``` ---------------------------------------- TITLE: Implementing Lambda Handler with Redis Golang DESCRIPTION: This Go code defines the AWS Lambda handler function for the serverless API. It initializes a Redis client, increments a counter key named 'count' in Redis, and returns the updated count as a JSON response. Placeholders for Redis endpoint and password must be replaced. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/goapi.mdx#_snippet_1 LANGUAGE: Golang CODE: ``` package main import ( "context" "encoding/json" "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" "github.com/go-redis/redis/v8" "strconv" ) var ctx = context.Background() type MyResponse struct { Count string `json:"count:"` } var rdb = redis.NewClient(&redis.Options{ Addr: "YOUR_REDIS_ENDPOINT", Password: "YOUR_REDIS_PASSWORD", DB: 0, }) func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { count, err := rdb.Incr(ctx, "count").Result() if err != nil { panic(err) } response := &MyResponse{ Count: strconv.FormatInt(count, 10), } body, err := json.Marshal(response) return events.APIGatewayProxyResponse{ Headers: map[string]string{"Content-Type": "application/json"}, Body: string(body), StatusCode: 200, }, nil } func main() { lambda.Start(handler) } ``` ---------------------------------------- TITLE: Creating Upstash QStash Receiver - TypeScript/JavaScript DESCRIPTION: Demonstrates how to initialize the @upstash/qstash Receiver using signing keys provided by environment variables. This client is used to verify the signature and body of incoming HTTP requests sent by QStash, ensuring they are legitimate. Requires the @upstash/qstash package. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/vercelintegration.mdx#_snippet_3 LANGUAGE: TypeScript CODE: ``` import { Receiver } from "@upstash/qstash"; const r = new Receiver({ currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY, nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY, }); const isValid = await r.verify( signature: "...", body: "..." }) ``` ---------------------------------------- TITLE: Setting Multiple Fields on a Redis Hash (TypeScript) DESCRIPTION: This code snippet demonstrates how to use a Redis client's hset method in TypeScript to set multiple fields and their values within a single hash key. It takes the hash key and an object containing the field-value pairs as arguments. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hset.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.hset("key", { id: 1, username: "chronark", name: "andreas" }); ``` ---------------------------------------- TITLE: Initializing BullMQ Queue and Adding Jobs (JavaScript) DESCRIPTION: Demonstrates how to create a BullMQ Queue instance configured with Upstash Redis connection details and add example jobs to the queue using the `add` method. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/bullmq.mdx#_snippet_1 LANGUAGE: javascript CODE: ``` import { Queue } from 'bullmq'; const myQueue = new Queue('foo', { connection: { host: "UPSTASH_REDIS_ENDPOINT", port: 6379, password: "UPSTASH_REDIS_PASSWORD", tls: {} }}); async function addJobs() { await myQueue.add('myJobName', { foo: 'bar' }); await myQueue.add('myJobName', { qux: 'baz' }); } await addJobs(); ``` ---------------------------------------- TITLE: Initialize Upstash Redis Python Client with Explicit Credentials DESCRIPTION: Demonstrates how to initialize instances of the Upstash Redis client (both synchronous and asynchronous versions) by explicitly providing the REST URL and token obtained from the Upstash console. This method is suitable when credentials are not stored in environment variables. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/gettingstarted.mdx#_snippet_1 LANGUAGE: python CODE: ``` # for sync client from upstash_redis import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") ``` LANGUAGE: python CODE: ``` # for async client from upstash_redis.asyncio import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") ``` ---------------------------------------- TITLE: Creating Serverless Project | AWS Java Maven | Shell DESCRIPTION: Initializes a new serverless project named 'counter-api' using the predefined AWS Java Maven template. This creates the basic project structure including pom.xml and serverless.yml. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/serverless_java_redis.mdx#_snippet_1 LANGUAGE: shell CODE: ``` serverless create --template aws-java-maven --name counter-api -p aws-java-counter-api ``` ---------------------------------------- TITLE: Manual Cache Invalidation by Custom Tag - TypeScript DESCRIPTION: Shows how to manually invalidate cached queries by providing a custom tag defined previously when the query was cached. This offers a flexible way to group and invalidate related cache entries. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/drizzle.mdx#_snippet_8 LANGUAGE: typescript CODE: ``` // 👇 invalidate all queries by custom tag (defined in previous queries) await db.$cache?.invalidate({ tags: ["custom_key"] }) ``` ---------------------------------------- TITLE: Sending PING to Redis in TypeScript DESCRIPTION: This snippet shows how to execute the PING command using a Redis client library in TypeScript (likely the @upstash/redis client based on context). It sends a PING request to the server and logs the received response, which is expected to be 'PONG' if the server is alive. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/auth/ping.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const response = await redis.ping(); console.log(response); // "PONG" ``` ---------------------------------------- TITLE: Ensuring Asynchronous Synchronization Completes (TypeScript) DESCRIPTION: Explains how to use the `pending` promise returned by the `limit` method with `context.waitUntil` in environments like Cloudflare Workers or Vercel Edge Functions to ensure asynchronous background tasks, such as multi-region replication, are completed before the function exits. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/features.mdx#_snippet_6 LANGUAGE: TypeScript CODE: ``` const { pending } = await ratelimit.limit("id"); context.waitUntil(pending); ``` ---------------------------------------- TITLE: Retrieving Multiple Keys (MGET) in TypeScript DESCRIPTION: Retrieves the values for multiple keys from Redis in a single operation. This command counts as a single billing unit regardless of the number of keys. If a key does not exist, its corresponding value in the result array will be null. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const values = await redis.mget("key1", "key2", "key3"); ``` ---------------------------------------- TITLE: Basic SET Command in Python DESCRIPTION: Demonstrates the basic usage of the Redis SET command in Python to set a key-value pair and then verifies the value using the GET command. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/set.mdx#_snippet_0 LANGUAGE: python CODE: ``` assert redis.set("key", "value") == True assert redis.get("key") == "value" ``` ---------------------------------------- TITLE: Removing Members from Redis Sorted Set in Python DESCRIPTION: This Python snippet demonstrates how to use the `zadd` command to initialize a Redis sorted set and then the `zrem` command to remove specified members. It includes an assertion to verify that the correct number of members (only 'one' in this case) were successfully removed. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zrem.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) assert redis.zrem("myset", "one", "four") == 1 ``` ---------------------------------------- TITLE: Using GETDEL command in Python DESCRIPTION: This snippet demonstrates using the Redis GETDEL command via a Python client. It first sets a key with a value, then uses GETDEL to retrieve the value and simultaneously delete the key, finally asserting that the key no longer exists. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/getdel.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.set("key", "value") assert redis.getdel("key") == "value" assert redis.get("key") == None ``` ---------------------------------------- TITLE: Calling Redis UNLINK Command in Python DESCRIPTION: Demonstrates how to call the `unlink` command on a Redis client object in Python. It takes one or more key names as arguments and asserts that the command returns the correct number of keys that were successfully unlinked asynchronously. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/unlink.mdx#_snippet_0 LANGUAGE: python CODE: ``` assert redis.unlink("key1", "key2", "key3") == 3 ``` ---------------------------------------- TITLE: Calling Celery Task Asynchronously (python) DESCRIPTION: Demonstrates how to import and call a Celery task (`add`) using the `.delay()` method for asynchronous execution. It then retrieves the task's state and final result using the `.get()` method, blocking until the result is available or a timeout occurs. Requires the Celery worker to be running and the `tasks` module containing the task definition. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/celery.mdx#_snippet_5 LANGUAGE: python CODE: ``` from tasks import add result = add.delay(4, 6) print(f"Task state: {result.state}") # Outputs 'PENDING' initially # Wait for the result output = result.get(timeout=10) print(f"Task result: {output}") # Outputs '10' ``` ---------------------------------------- TITLE: Performing MGET on Redis (Python) DESCRIPTION: This snippet demonstrates how to use the MGET command with a Python Redis client. It first sets two keys, 'key1' and 'key2', with corresponding values. Then, it calls mget with these two keys and uses an assertion to verify that the returned list contains the expected values in the correct order. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/mget.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.set("key1", "value1") redis.set("key2", "value2") assert redis.mget("key1", "key2") == ["value1", "value2"] ``` ---------------------------------------- TITLE: Configuring Serverless Service and Function (YAML) DESCRIPTION: This YAML file configures the Serverless service, specifying the AWS provider, Node.js runtime, and passing environment variables from the host (.env file) to the Lambda function. It defines the 'ratelimit' function and configures it to be triggered by a GET request to the root path. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/rate-limiting.mdx#_snippet_6 LANGUAGE: yaml CODE: ``` service: ratelimit-serverless provider: name: aws runtime: nodejs20.x environment: UPSTASH_REDIS_REST_URL: ${env:UPSTASH_REDIS_REST_URL} UPSTASH_REDIS_REST_TOKEN: ${env:UPSTASH_REDIS_REST_TOKEN} functions: ratelimit: handler: handler.ratelimit events: - httpApi: path: / method: get ``` ---------------------------------------- TITLE: Applying EXPIREAT using Redis Client in TypeScript DESCRIPTION: Demonstrates setting a key and then applying an expiration using the EXPIREAT command via a Redis client in TypeScript. It shows how to calculate a future Unix timestamp and pass it to the `expireat` method. Requires an initialized Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/expireat.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.set("mykey", "Hello"); const tenSecondsFromNow = Math.floor(Date.now() / 1000) + 10; await redis.expireat("mykey", tenSecondsFromNow); ``` ---------------------------------------- TITLE: Getting JSON Value from Redis in Python DESCRIPTION: This snippet demonstrates how to use the `json.get` method from a Python Redis client to retrieve a specific value from a JSON document stored under a given key, specifying the path to the desired value. The function returns the value at the specified path or `null` if the path does not exist. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/get.mdx#_snippet_0 LANGUAGE: Python CODE: ``` value = redis.json.get("key", "$.path.to.somewhere") ``` ---------------------------------------- TITLE: Performing ZUNIONSTORE with Weights in TypeScript DESCRIPTION: This snippet shows how to use the ZUNIONSTORE command with the 'weights' option in TypeScript. After populating two sorted sets, it performs the union while applying specific weights to the scores from each input set before combining them, storing the result in 'destination', and logging the element count. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zunionstore.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zunionstore( "destination", 2, ["key1", "key2"], { weights: [2, 3] }, ); console.log(res) // 2 ``` ---------------------------------------- TITLE: Configuring Ephemeral Cache with Ratelimit (TypeScript) DESCRIPTION: Demonstrates how to configure an in-memory ephemeral cache using a JavaScript Map to reduce calls to Redis for blocked identifiers in hot serverless functions. The cache must be initialized outside the function handler. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/features.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` const cache = new Map(); // must be outside of your serverless function handler // ... const ratelimit = new Ratelimit({ // ... ephemeralCache: cache, }); ``` ---------------------------------------- TITLE: Connecting Redigo Client (Go) DESCRIPTION: This snippet shows how to connect the `redigo` client to an Upstash Redis database in Go. It uses `redis.Dial` with a TCP endpoint, enabling TLS via `redis.DialUseTLS(true)`. Authentication is done using the `AUTH` command via `c.Do`. The example includes error handling and demonstrates `SET` and `GET` operations. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/connectclient.mdx#_snippet_4 LANGUAGE: go CODE: ``` func main() { c, err := redis.Dial("tcp", "YOUR_ENDPOINT:YOUR_PORT", redis.DialUseTLS(true)) if err != nil { panic(err) } _, err = c.Do("AUTH", "YOUR_PASSWORD") if err != nil { panic(err) } _, err = c.Do("SET", "foo", "bar") if err != nil { panic(err) } value, err := redis.String(c.Do("GET", "foo")) if err != nil { panic(err) } println(value) } ``` ---------------------------------------- TITLE: Setting Multiple Keys (MSET) in TypeScript DESCRIPTION: Sets multiple key-value pairs in Redis in a single atomic operation. This command counts as a single billing unit. The input is an object where keys are Redis keys and values are the data to be stored. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.mset({ key1: { a: 1 }, key2: "value2", key3: true, }); ``` ---------------------------------------- TITLE: Scanning Redis Keys with Wildcard Pattern (TypeScript) DESCRIPTION: Demonstrates how to start a basic scan operation on a Redis database using a client library. It begins with cursor `0` and uses the wildcard pattern `*` to match all keys, retrieving the first batch of results. Requires an initialized Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/scan.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const [cursor, keys] = await redis.scan(0, { match: "*" }); ``` ---------------------------------------- TITLE: Executing JSON.MGET with Upstash Redis Client - TypeScript DESCRIPTION: This snippet demonstrates how to use the `json.mget` method of the Upstash Redis TypeScript client. It retrieves the value at the specified JSON `path` from multiple keys provided in the `keys` array. The result is an array containing the values found at the path for each key, or `null` if the path doesn't exist for a given key. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/mget.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const values = await redis.json.mget(["key1", "key2"], "$.path.to.somewhere"); ``` ---------------------------------------- TITLE: Iterating ZSCAN Results - Python DESCRIPTION: Demonstrates how to use the ZSCAN command within a loop to retrieve all members and their scores from a Redis sorted set, handling pagination by using the returned cursor. It initializes the cursor to 0 and continues calling ZSCAN until the cursor returned is 0, collecting results in a list. Finally, it prints the retrieved key-score pairs. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zscan.mdx#_snippet_0 LANGUAGE: Python CODE: ``` # Get all elements of an ordered set. cursor = 0 results = [] while True: cursor, keys = redis.zscan("myzset", cursor, match="*") results.extend(keys) if cursor == 0: break for key, score in results: print(key, score) ``` ---------------------------------------- TITLE: Using Cache::flexible Method (PHP) DESCRIPTION: Illustrates the use of `Cache::flexible` for implementing the stale-while-revalidate caching pattern, serving cached data immediately while asynchronously refreshing it if it's within the stale period. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/laravel_caching.mdx#_snippet_14 LANGUAGE: php CODE: ``` $value = Cache::flexible('todos', [5, 10], function () { return Todo::all(); }); ``` ---------------------------------------- TITLE: Defining Increment API Endpoint - JavaScript DESCRIPTION: This Nuxt server API endpoint initializes an Upstash Redis client, increments a counter ('api_call_counter'), retrieves the last call time ('last_called'), updates it to the current time, and returns the count and last called time. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/nuxtjs_with_redis.mdx#_snippet_5 LANGUAGE: javascript CODE: ``` import { defineEventHandler } from "h3"; import { Redis } from "@upstash/redis"; // Initialize Redis const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL || "", token: process.env.UPSTASH_REDIS_REST_TOKEN || "" }); export default defineEventHandler(async () => { const identifier = "api_call_counter"; try { // Increment the API call counter and get the updated value const count = await redis.incr(identifier); // Optionally, you can also retrieve other information like the last time it was called const lastCalled = await redis.get("last_called"); const lastCalledAt = lastCalled || "Never"; // Store the current timestamp as the last called time await redis.set("last_called", new Date().toISOString()); // Return the count and last called time return { success: true, count: count, lastCalled: lastCalledAt, }; } catch (error) { console.error("Redis error:", error); return { success: false, message: "Error interacting with Redis", }; } }); ``` ---------------------------------------- TITLE: Removing Keys from Array - Upstash Redis TypeScript DESCRIPTION: Shows how to use the `del` command with an array of keys in TypeScript. It utilizes the spread syntax (`...`) to pass the elements of the array as arguments to the `del` method. Useful when keys are stored in a list. Requires an initialized Upstash Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/del.mdx#_snippet_1 LANGUAGE: ts CODE: ``` const keys = ["key1", "key2"]; await redis.del(...keys) ``` ---------------------------------------- TITLE: Interacting with Redis using Laravel Facade PHP DESCRIPTION: This PHP snippet demonstrates how to use Laravel's Redis Facade to store and retrieve data from the configured Redis instance. It requires the Illuminate\Support\Facades\Redis facade. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/laravel.mdx#_snippet_4 LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\Redis; // Storing a value in Redis Redis::set('key', 'value'); // Retrieving a value from Redis $value = Redis::get('key'); ``` ---------------------------------------- TITLE: Defining Lambda Stack - AWS CDK TypeScript DESCRIPTION: Defines an AWS CDK stack that provisions the Lambda function. It specifies the function's code location, runtime, handler, environment variables for Upstash connection, bundling process including dependency installation, and adds a Function URL trigger. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/python-aws-lambda.mdx#_snippet_5 LANGUAGE: typescript CODE: ``` import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as path from 'path'; export class CounterCdkStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const counterFunction = new lambda.Function(this, 'CounterFunction', { code: lambda.Code.fromAsset(path.join(__dirname, 'api'), { bundling: { image: lambda.Runtime.PYTHON_3_9.bundlingImage, command: [ 'bash', '-c', 'pip install -r requirements.txt -t /asset-output && cp -au . /asset-output' ], }, }), runtime: lambda.Runtime.PYTHON_3_9, handler: 'index.handler', environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || '', UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || '', }, }); const counterFunctionUrl = counterFunction.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, }); new cdk.CfnOutput(this, "counterFunctionUrlOutput", { value: counterFunctionUrl.url, }) } } ``` ---------------------------------------- TITLE: Initializing Regional Sliding Window Ratelimit (TypeScript) DESCRIPTION: Initializes a regional Ratelimit instance using the slidingWindow algorithm. It connects to Redis via `Redis.fromEnv()` and configures the limiter to allow 10 requests per 10 seconds using a rolling window approach. Requires the `@upstash/ratelimit` and `@upstash/redis` libraries. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/algorithms.mdx#_snippet_3 LANGUAGE: typescript CODE: ``` const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), }); ``` ---------------------------------------- TITLE: Defining AWS SAM Template with Upstash Variables (YAML) DESCRIPTION: This YAML snippet represents the AWS SAM template file (`template.yaml`). It defines the serverless resources, including the Lambda function (`HelloWorldFunction`), its code location, handler, runtime, and API Gateway event trigger. Crucially, it defines parameters for `UpstashRedisRestURL` and `UpstashRedisRestToken` and maps them to environment variables within the Lambda function. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/using_aws_sam.mdx#_snippet_4 LANGUAGE: yaml CODE: ``` AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: |- sam-app Sample SAM Template for sam-app Globals: Function: Timeout: 3 MemorySize: 128 Parameters: UpstashRedisRestURL: Type: String UpstashRedisRestToken: Type: String Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: CodeUri: hello_world/ Handler: app.lambda_handler Runtime: python3.9 Architectures: - x86_64 Events: HelloWorld: Type: Api Properties: Path: /hello Method: get Environment: Variables: UPSTASH_REDIS_REST_URL: !Ref UpstashRedisRestURL UPSTASH_REDIS_REST_TOKEN: !Ref UpstashRedisRestToken Outputs: HelloWorldApi: Description: "API Gateway endpoint URL for Prod stage for Hello World function" Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" HelloWorldFunction: Description: "Hello World Lambda Function ARN" Value: !GetAtt HelloWorldFunction.Arn HelloWorldFunctionIamRole: Description: "Implicit IAM Role created for Hello World function" Value: !GetAtt HelloWorldFunctionRole.Arn ``` ---------------------------------------- TITLE: Configuring Upstash Ratelimit Plugin in Strapi DESCRIPTION: Configures the Upstash Ratelimit plugin within Strapi's plugin configuration file. This snippet enables the plugin, sets connection details from environment variables, and defines a basic rate limiting strategy (e.g., fixed window, 10 tokens per 20 seconds) for specific HTTP methods and paths. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/integrations/strapi/getting-started.mdx#_snippet_2 LANGUAGE: typescript CODE: ``` export default () => ({ "strapi-plugin-upstash-ratelimit": { enabled: true, resolve: "./src/plugins/strapi-plugin-upstash-ratelimit", config: { enabled: true, token: process.env.UPSTASH_REDIS_REST_TOKEN, url: process.env.UPSTASH_REDIS_REST_URL, strategy: [ { methods: ["GET", "POST"], path: "*", limiter: { algorithm: "fixed-window", tokens: 10, window: "20s", }, }, ], prefix: "@strapi", }, }, }); ``` LANGUAGE: javascript CODE: ``` module.exports = () => ({ "strapi-plugin-upstash-ratelimit": { enabled: true, resolve: "./src/plugins/strapi-plugin-upstash-ratelimit", config: { enabled: true, token: process.env.UPSTASH_REDIS_REST_TOKEN, url: process.env.UPSTASH_REDIS_REST_URL, strategy: [ { methods: ["GET", "POST"], path: "*", limiter: { algorithm: "fixed-window", tokens: 10, window: "20s", }, }, ], prefix: "@strapi", }, }, }); ``` ---------------------------------------- TITLE: Configuring Upstash Ratelimit Plugin - TypeScript DESCRIPTION: Add the Upstash Ratelimit plugin configuration to your Strapi project's `config/plugins.ts` file. This configuration enables the plugin and defines rate limiting strategies based on HTTP methods, paths, and specific limiter algorithms like fixed-window. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/ratelimit/strapi/getting-started.mdx#_snippet_2 LANGUAGE: typescript CODE: ``` export default () => ({ "strapi-plugin-upstash-ratelimit": { enabled: true, resolve: "./src/plugins/strapi-plugin-upstash-ratelimit", config: { enabled: true, token: process.env.UPSTASH_REDIS_REST_TOKEN, url: process.env.UPSTASH_REDIS_REST_URL, strategy: [ { methods: ["GET", "POST"], path: "*", limiter: { algorithm: "fixed-window", tokens: 10, window: "20s", }, }, ], prefix: "@strapi", }, }, }); ``` ---------------------------------------- TITLE: Configuring Upstash Redis Environment Variables in Wrangler TOML (YAML) DESCRIPTION: This configuration snippet shows how to manually define the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN environment variables in your Cloudflare Worker's wrangler.toml file under the [vars] section. These variables are used by the Redis.fromEnv() method in the worker code to establish the connection. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/cloudflareworkers.mdx#_snippet_2 LANGUAGE: yaml CODE: ``` [vars] UPSTASH_REDIS_REST_URL="REPLACE_HERE" UPSTASH_REDIS_REST_TOKEN="REPLACE_HERE" ``` ---------------------------------------- TITLE: Retrieving List Elements using LRANGE - TypeScript DESCRIPTION: This snippet demonstrates how to use the `lrange` command in TypeScript with a Redis client. It first pushes elements 'a', 'b', and 'c' to a list named 'key' using `lpush` and then retrieves a specific range of elements (from index 1 to 2, inclusive) from that list using `lrange`. The retrieved elements are then printed to the console. This requires a configured Redis client instance, likely from the Upstash SDK. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/lrange.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.lpush("key", "a", "b", "c"); const elements = await redis.lrange("key", 1, 2); console.log(elements) // ["b", "c"] ``` ---------------------------------------- TITLE: Handle Ratelimit Pending Promise in Workers - TypeScript DESCRIPTION: Demonstrates how to use `context.waitUntil` with the `pending` promise returned by `ratelimit.limit` in Vercel Edge or Cloudflare Workers environments. This ensures background operations complete before the function exits. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/methods.mdx#_snippet_2 LANGUAGE: TypeScript CODE: ``` const { pending } = await ratelimit.limit("id") context.waitUntil(pending) ``` ---------------------------------------- TITLE: Setting List Element with Upstash Redis (TypeScript) DESCRIPTION: This snippet demonstrates using the Upstash Redis client (`redis`) to first push elements onto a list (`lpush`) and then set the value of an element at a specific index (`lset`). It shows the effect of replacing the element at index 1 (0-based) with a new value. Requires an initialized `redis` client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/lset.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.lpush("key", "a", "b", "c"); await redis.lset("key", 1, "d"); // list is now ["a", "d", "c"] ``` ---------------------------------------- TITLE: Fetching Multiple Keys with MGET (TypeScript) DESCRIPTION: This TypeScript code snippet demonstrates using the `redis.mget` method to retrieve multiple key-value pairs from Redis in a single operation. It shows how to define a custom type `MyType` for the expected values and casts the result using a type parameter. The example fetches keys "key1", "key2", and "key3", expecting an array of `MyType` objects or `null`. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/mget.mdx#_snippet_0 LANGUAGE: ts CODE: ``` type MyType = { a: number; b: string; }; const values = await redis.mget("key1", "key2", "key3"); // values.length -> 3 ``` ---------------------------------------- TITLE: Publishing Message to Channel with Redis (TypeScript) DESCRIPTION: This snippet demonstrates publishing a message to a specified channel using a Redis client library. It calls the `publish` method with the channel name ("my-topic") and the message content ("my-message"), storing the number of receiving clients in the `listeners` variable. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/pubsub/publish.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const listeners = await redis.publish("my-topic", "my-message"); ``` ---------------------------------------- TITLE: Getting Key Expiration using Upstash Redis Client (TypeScript) DESCRIPTION: This snippet demonstrates how to use the `ttl` method on a Upstash Redis client instance to retrieve the time-to-live (TTL) for a specified key. The method returns a promise that resolves to the number of seconds remaining until the key expires, or a negative value if the key does not exist or has no associated expiration. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/ttl.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const seconds = await redis.ttl(key); ``` ---------------------------------------- TITLE: Reading Stream Entries with XRANGE in Python DESCRIPTION: This snippet demonstrates how to use the `xrange` method of a Redis client library in Python to fetch stream entries within a specified ID range. It queries the full range of IDs from '-' (start) to '+' (end) for a given key and prints the resulting dictionary of entries. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/stream/xrange.mdx#_snippet_0 LANGUAGE: python CODE: ``` entries = redis.xrange(key, "-", "+") print(entries) # { # "1548149259438-0": { # "field1": "value1", # "field2": "value2" # }, # "1548149259438-1": { # "field1": "value3", # "field2": "value4" # } # } ``` ---------------------------------------- TITLE: Querying Stream Range with TypeScript DESCRIPTION: This snippet demonstrates how to use the `xrange` method provided by a Redis client library (like Upstash Redis) to fetch entries from a stream within a specified ID range. It shows fetching all entries using '-' and '+' for the start and end IDs and logs the resulting object structure. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/stream/xrange.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const entries = redis.xrange(key, "-", "+"); console.log(entries) // { // "1548149259438-0": { // "field1": "value1", // "field2": "value2" // }, // "1548149259438-1": { // "field1": "value3", // "field2": "value4" // } // } ``` ---------------------------------------- TITLE: Creating Upstash Redis on Fly.io (flyctl Shell) DESCRIPTION: Demonstrates using the `flyctl redis create` command line interface to provision an Upstash Redis database within the Fly.io platform. Guides through the interactive prompts for configuration details like organization, region, naming, and scaling options. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/fly.mdx#_snippet_0 LANGUAGE: shell CODE: ``` flyctl redis create ``` ---------------------------------------- TITLE: Performing ZUNIONSTORE with Aggregation in TypeScript DESCRIPTION: This snippet illustrates the use of the ZUNIONSTORE command with the 'aggregate' option (specifically 'sum') in TypeScript. It populates two sorted sets and then performs the union, summing the scores for members that appear in multiple input sets before storing the result in 'destination' and logging the element count. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zunionstore.mdx#_snippet_2 LANGUAGE: ts CODE: ``` await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zunionstore( "destination", 2, ["key1", "key2"], { aggregate: "sum" }, ); console.log(res) // 2 ``` ---------------------------------------- TITLE: Merging JSON value using Upstash Redis Python DESCRIPTION: This snippet demonstrates how to use the `redis.json.merge` command in Python to merge a JSON value into an existing JSON structure stored in a Redis key at a specified path. It takes the key name, the target path, and the JSON value to merge as arguments. The operation returns `true` upon successful completion. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/merge.mdx#_snippet_0 LANGUAGE: py CODE: ``` redis.json.merge("key", "$.path.to.value", {"new": "value"}) ``` ---------------------------------------- TITLE: Setting Up Upstash Redis Environment Variables - Shell DESCRIPTION: Configure your Strapi project's `.env` file with the connection details for your Upstash Redis database. Replace the placeholder values with the actual token and URL obtained from the Upstash Console. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/ratelimit/strapi/getting-started.mdx#_snippet_1 LANGUAGE: shell CODE: ``` UPSTASH_REDIS_REST_TOKEN="" UPSTASH_REDIS_REST_URL="" ``` ---------------------------------------- TITLE: Implementing Counter Logic Google Cloud Function JavaScript DESCRIPTION: This JavaScript code defines the main logic for the Google Cloud Function named 'counter'. It initializes an Upstash Redis client using environment variables for connection details, increments a key named "counter" in the Redis database, and returns the updated count via an HTTP response. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/google-cloud-functions.mdx#_snippet_0 LANGUAGE: javascript CODE: ``` const { Redis } = require("@upstash/redis"); const functions = require('@google-cloud/functions-framework'); const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN }); functions.http('counter', async (req, res) => { const count = await redis.incr("counter"); res.send("Counter:" + count); }); ``` ---------------------------------------- TITLE: Using ZUNIONSTORE Command in Python DESCRIPTION: This snippet demonstrates the basic usage of the Redis zunionstore command in Python. It adds elements to two sorted sets (key1 and key2) and then computes the union, storing the result implicitly. The result is the number of elements in the resulting set. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zunionstore.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zunionstore(["key1", "key2"]) assert result == 5 ``` ---------------------------------------- TITLE: Getting All Set Members using Redis in Python DESCRIPTION: This snippet demonstrates how to add multiple members to a Redis set using the `SADD` command and subsequently retrieve all members of that set using the `SMEMBERS` command in Python. It includes an assertion to verify that the returned set contains the expected elements. It assumes a connected Redis client instance named `redis`. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/smembers.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.sadd("set", "a", "b", "c"); assert redis.smembers("set") == {"a", "b", "c"} ``` ---------------------------------------- TITLE: Merging JSON in Redis using TypeScript Client DESCRIPTION: This snippet demonstrates how to use a TypeScript Redis client to perform a JSON merge operation. It merges the provided JSON object {"new": "value"} into the document located at the specified key "key" and path "$.path.to.value". This operation requires a Redis instance with the RediSearch/RedisJSON module enabled and a compatible client library. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/merge.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.json.merge("key", "$.path.to.value", {"new": "value"}) ``` ---------------------------------------- TITLE: Publishing Message to Redis Channel via REST (Shell) DESCRIPTION: Shows how to use curl to publish a message (hello) to a specific Redis channel (chat) using the Upstash REST API's /publish/{channel}/{message} endpoint. It includes setting the Authorization header. SOURCE: https://github.com/upstash/docs/blob/main/redis/features/restapi.mdx#_snippet_9 LANGUAGE: shell CODE: ``` curl -X POST https://us1-merry-cat-32748.upstash.io/publish/chat/hello \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" ``` ---------------------------------------- TITLE: Implementing Fastly Compute@Edge Handler with Upstash Redis (JavaScript) DESCRIPTION: This snippet defines the Fastly Compute@Edge fetch event handler. It initializes the @upstash/redis/fastly client using a URL, token, and the defined Fastly backend name ("upstash"). It then performs a simple `incr` operation on a Redis key "count" and returns the incremented value in the HTTP response. It requires the @upstash/redis package and a Fastly backend configured for the Upstash Redis endpoint. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/fastlycompute.mdx#_snippet_0 LANGUAGE: JavaScript CODE: ``` import { Redis } from "@upstash/redis/fastly"; addEventListener("fetch", (event) => event.respondWith(handleRequest(event))); async function handleRequest(event) { const redis = new Redis({ url: "UPSTASH_REDIS_REST_URL", token: "UPSTASH_REDIS_REST_TOKEN", backend: "upstash", }); const data = await redis.incr("count"); return new Response("View Count:" + data, { status: 200 }); } ``` ---------------------------------------- TITLE: Storing Redis Sorted Set Intersection (Weights) - TypeScript DESCRIPTION: This example illustrates how to use the 'weights' option with the zinterstore command. After setting up two sorted sets, it computes their intersection and stores the result in 'destination'. It applies specific weights ([2, 3]) to the scores of elements originating from 'key1' and 'key2' respectively before aggregation. The final count of elements in the result set is then logged. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zinterstore.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zinterstore( "destination", 2, ["key1", "key2"], { weights: [2, 3] }, ); console.log(res) // 1 ``` ---------------------------------------- TITLE: Configuring Upstash Ratelimit Strategy for All Routes with IP - JSON DESCRIPTION: This JSON snippet illustrates configuring the Upstash Ratelimit Strapi plugin to apply a fixed-window rate limit to all GET and POST requests (`path: "*"`), using the client's IP address (`identifierSource: "ip"`) as the unique identifier. This configuration requires the plugin to be installed and configured with valid Upstash Redis REST credentials. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/ratelimit/strapi/configurations.mdx#_snippet_1 LANGUAGE: json CODE: ``` { "strapi-plugin-upstash-ratelimit": { "enabled": true, "resolve": "./src/plugins/strapi-plugin-upstash-ratelimit", "config": { "enabled": true, "token": "process.env.UPSTASH_REDIS_REST_TOKEN", "url": "process.env.UPSTASH_REDIS_REST_URL", "strategy": [ { "methods": ["GET", "POST"], "path": "*", "identifierSource": "ip", "limiter": { "algorithm": "fixed-window", "tokens": 10, "window": "20s" } } ], "prefix": "@strapi" } } } ``` ---------------------------------------- TITLE: Conditional Redis Connection URL (Node.js) DESCRIPTION: Shows a Node.js code pattern for setting the Redis connection URL conditionally based on the application's environment (`process.env.NODE_ENV`). It uses a predefined local tunnel address (e.g., `redis://localhost:10000`) during local development and falls back to the standard `REDIS_URL` environment variable when deployed, typically to Fly.io. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/fly.mdx#_snippet_4 LANGUAGE: javascript CODE: ``` const redis = require("redis"); // Local Redis URL for development const LOCAL_REDIS_URL = 'redis://localhost:10000'; // Replace with your actual local address const REDIS_URL = process.env.NODE_ENV === 'development' ? LOCAL_REDIS_URL : process.env.REDIS_URL; const client = redis.createClient({ url: REDIS_URL }); client.on("error", function(error) { console.error(error); }); // Rest of your Redis-related code ``` ---------------------------------------- TITLE: Executing JSON.MGET Command in Python DESCRIPTION: This snippet demonstrates how to use the `json.mget` method in Python to retrieve values from a specified path (`$.path.to.somewhere`) across multiple keys (`["key1", "key2"]`). It assumes you have a Redis/Upstash client instance named `redis` and that keys "key1" and "key2" contain JSON data. The result, a list of values or nulls, is stored in the `values` variable. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/mget.mdx#_snippet_0 LANGUAGE: python CODE: ``` values = redis.json.mget(["key1", "key2"], "$.path.to.somewhere") ``` ---------------------------------------- TITLE: Configuring Upstash Redis Connection in .env DESCRIPTION: These .env variables configure the connection details for the Redis database. Replace the placeholder values with your actual Upstash Redis endpoint, port (usually 6379), and password obtained from the Upstash Console. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/laravel.mdx#_snippet_3 LANGUAGE: .env CODE: ``` REDIS_HOST="" REDIS_PORT=6379 REDIS_PASSWORD="" ``` ---------------------------------------- TITLE: Check Member Existence in Redis Set (Python) DESCRIPTION: Demonstrates adding members to a Redis set using `sadd` and then verifying if a specific member exists within that set using `sismember`. It requires a Redis client instance (`redis`). The snippet adds 'a', 'b', 'c' to set 'set' and asserts that 'a' is a member. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/sismember.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.sadd("set", "a", "b", "c") assert redis.sismember("set", "a") == True ``` ---------------------------------------- TITLE: Simple ZINTERSTORE using Python DESCRIPTION: This snippet shows a basic usage of the `zinterstore` command in Python. It first adds members to two sorted sets (`key1` and `key2`) and then calculates their intersection, storing the result in the `dest` key. It asserts that the resulting set contains one element, which is 'c' in this case. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zinterstore.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zinterstore("dest", ["key1", "key2"]) assert result == 1 ``` ---------------------------------------- TITLE: Using Redis ZREVRANK in Python DESCRIPTION: This snippet demonstrates how to use the ZREVRANK command in Python. It first populates a sorted set named 'myset' with members and scores using ZADD, and then calls zrevrank to retrieve the reverse rank of the member 'a'. The assertion verifies that the reverse rank is 2, as 'a' has the lowest score (1) in the set ('c':3, 'b':2, 'a':1). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zrevrank.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrevrank("myset", "a") == 2 ``` ---------------------------------------- TITLE: Using Upstash Redis SINTERSTORE in TypeScript DESCRIPTION: This snippet demonstrates how to use the Upstash Redis client in TypeScript to add members to two sets (`set1`, `set2`) and then perform the SINTERSTORE operation. The intersection of `set1` and `set2` is calculated and stored in the `destination` key. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/sinterstore.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); await redis.sinterstore("destination", "set1", "set2"); ``` ---------------------------------------- TITLE: Executing MSETNX Redis Command in Python DESCRIPTION: This snippet demonstrates how to use the MSETNX command in Python to set multiple key-value pairs simultaneously. It takes a dictionary where keys are Redis keys and values are their corresponding values. The command will only succeed and return 1 if all specified keys do not already exist in the database; otherwise, it returns 0. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/msetnx.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.msetnx({ key1: 1, key2: "hello", key3: { a: 1, b: "hello" }, }) ``` ---------------------------------------- TITLE: Adding Only New Members to Sorted Set (TypeScript) DESCRIPTION: Illustrates using the ZADD command with the `nx` option to only add new members to the sorted set, ignoring members that already exist. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zadd.mdx#_snippet_2 LANGUAGE: ts CODE: ``` await redis.zadd( "key", { nx: true }, { score: 2, member: "member" }, ) ``` ---------------------------------------- TITLE: Removing Sorted Set Members Lexicographically with TypeScript DESCRIPTION: This snippet demonstrates how to use the `zremrangebylex` command with a TypeScript Redis client. It removes elements from the sorted set named "key" that fall within the lexicographical range from "alpha" up to "omega", inclusive. The operation is asynchronous and requires awaiting the result. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zremrangebylex.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.zremrangebylex("key", "alpha", "omega") ``` ---------------------------------------- TITLE: Publishing Message to Channel in Python DESCRIPTION: This snippet demonstrates how to publish a message to a Redis channel using a Python client. It calls the `publish` method on a Redis client instance, specifying the channel name and the message payload. The method returns the number of clients currently subscribed to the channel who received the message. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/pubsub/publish.mdx#_snippet_0 LANGUAGE: python CODE: ``` listeners = redis.publish("my-topic", "my-message") ``` ---------------------------------------- TITLE: Querying Sorted Set Range By Score in Python DESCRIPTION: Shows how to use the `sortby="BYSCORE"` parameter with ZRANGE to explicitly request elements sorted by score, which is the default behavior. Requires an initialized Redis client and a sorted set with data. It adds elements and asserts the range [0, 1] sorted by score returns expected values. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zrange.mdx#_snippet_2 LANGUAGE: python CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrange("myset", 0, 1, sortby="BYSCORE") == ["a", "b"] ``` ---------------------------------------- TITLE: Getting all values from a Redis Hash using Python DESCRIPTION: This snippet demonstrates how to set values within a Redis hash using `hset` and subsequently retrieve all values from that hash using the `hvals` command with the Upstash Redis Python client. It includes an assertion to verify the retrieved values. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hvals.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hvals("myhash") == ["Hello", "World"] ``` ---------------------------------------- TITLE: Getting Hash Field Count with Upstash Redis (TypeScript) DESCRIPTION: This snippet demonstrates how to use the Upstash Redis client in TypeScript to first set fields in a hash using `hset` and then retrieve the total number of fields in that hash using `hlen`. It requires an initialized Upstash Redis client instance. The output is the integer count of fields. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hlen.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.hset("key", { id: 1, username: "chronark", }); const fields = await redis.hlen("key"); console.log(fields); // 2 ``` ---------------------------------------- TITLE: Querying Hash Keys (HKEYS) in TypeScript with Upstash Redis DESCRIPTION: This snippet demonstrates how to use the Upstash Redis client in TypeScript to first set values in a hash using `hset`, and then retrieve all the field names from that hash using the `hkeys` command. It shows the expected output `["id", "username"]` when querying the 'key' hash. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hkeys.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.hset("key", { id: 1, username: "chronark", }); const fields = await redis.hkeys("key"); console.log(fields); // ["id", "username"] ``` ---------------------------------------- TITLE: Using GETDEL with Upstash Redis (TypeScript) DESCRIPTION: Demonstrates calling the `getdel` method on an Upstash Redis client instance. It shows how to retrieve and delete a key, optionally casting the result to a specific TypeScript type. Requires an initialized Upstash Redis client. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/getdel.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` type MyType = { a: number; b: string; } await redis.getdel("key"); // returns {a: 1, b: "2"} ``` ---------------------------------------- TITLE: Performing Simple Redis ZUNION in Python DESCRIPTION: Demonstrates a basic ZUNION operation on two sorted sets using a Python client. It adds elements to 'key1' and 'key2' and then performs a union, showing the combined elements without scores. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zunion.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zunion(["key1", "key2"]) assert result == ["a", "b", "c", "d", "e"] ``` ---------------------------------------- TITLE: Fetching and Displaying Coin List - JavaScript/React DESCRIPTION: This Next.js page component (`index.js`) defines a GraphQL query to fetch elements from the 'coins' Redis list using the `redisLRange` field provided by the Upstash GraphQL API. It utilizes the `useQuery` hook from Apollo Client to execute the query and manage loading/error states. The fetched data, which consists of JSON strings, is parsed, and the coin details are rendered in an HTML table, providing a dynamic coin price list. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/coin_price_list.mdx#_snippet_2 LANGUAGE: javascript CODE: ``` import Head from "next/head"; import styles from "../styles/Home.module.css"; import { gql, useQuery } from "@apollo/client"; import React from "react"; const GET_COIN_LIST = gql` query { redisLRange(key: "coins", start: 0, stop: 6) } `; export default function Home() { let coins = []; const { loading, error, data } = useQuery(GET_COIN_LIST); if (!loading && !error) { for (let x of data.redisLRange) { let dd = JSON.parse(x); coins.push(dd); } } return (
Create Next App

Coin Price List

{!loading ? ( coins.map((item, ind) => ( )) ) : ( )}
{item.name} ${item.price}
); } ``` ---------------------------------------- TITLE: Popping Default Element from JSON Array - TypeScript DESCRIPTION: Demonstrates popping the last element (default behavior when index is omitted or -1) from a JSON array located at a specified path within a Redis key using a TypeScript client method. It requires a Redis connection and a key containing a JSON array. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/arrpop.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const element = await redis.json.arrpop("key", "$.path.to.array"); ``` ---------------------------------------- TITLE: Getting Key Type with Redis Python Client DESCRIPTION: This snippet demonstrates how to use the TYPE command via a Python Redis client. It shows setting keys with string and list types, then asserting the type returned by `redis.type()`. It also includes an example checking the type of a non-existent key, which correctly returns 'none'. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/type.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.set("key1", "Hello") assert redis.type("key1") == "string" redis.lpush("key2", "Hello") assert redis.type("key2") == "list" assert redis.type("non-existent-key") == "none" ``` ---------------------------------------- TITLE: Creating Upstash Database Resource HCL DESCRIPTION: This snippet defines an Upstash database resource using the configured provider. You must specify the database name, the AWS region for deployment, and the database type (e.g., "free"). SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/terraformprovider.mdx#_snippet_1 LANGUAGE: HCL CODE: ``` resource "upstash_database" "mydb" { database_name = "testdblstr" region = "eu-west-1" type = "free" } ``` ---------------------------------------- TITLE: Checking Script Existence using Upstash Redis Client - TypeScript DESCRIPTION: This snippet demonstrates how to use a TypeScript Redis client (like `@upstash/redis`) to check for the existence of multiple scripts in the Redis script cache. The `scriptExists` method takes one or more SHA-1 hashes as string arguments and returns an array of numbers. A value of `1` indicates the script exists in the cache, while `0` means it does not. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/scripts/script_exists.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.scriptExists("", "") // Returns 1 // [1, 0] ``` ---------------------------------------- TITLE: Incrementing Key using Upstash Redis Python Client DESCRIPTION: This Python snippet demonstrates how to use a Redis client (presumably Upstash's) to first set an integer value to a key using `set()` and then increment that value using the `incr()` method, asserting that the result is the expected incremented value. It requires an initialized `redis` client object. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/incr.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.set("key", 6) assert redis.incr("key") == 7 ``` ---------------------------------------- TITLE: Initialize Redis Database with Data Node.js DESCRIPTION: Script for populating the Redis database with initial data (country names and their prefixes). It reads the Redis URL from environment variables and uses `ioredis` to add terms to a sorted set named 'terms'. Each term and its prefixes are added with a score of 0, and completed terms are marked with an asterisk (*). SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/auto_complete_with_serverless_redis.mdx#_snippet_6 LANGUAGE: javascript CODE: ``` require('dotenv').config() var Redis = require("ioredis"); var countries = [ {"name": "Afghanistan", "code": "AF"}, {"name": "Åland Islands", "code": "AX"}, {"name": "Albania", "code": "AL"}, {"name": "Algeria", "code": "DZ"}, ... ] var client = new Redis(process.env.REDIS_URL); for (const country of countries) { let term = country.name.toUpperCase(); let terms = []; for (let i = 1; i < term.length; i++) { terms.push(0); terms.push(term.substring(0, i)); } terms.push(0); terms.push(term + "*"); (async () => { await client.zadd("terms", ...terms) })(); } ``` ---------------------------------------- TITLE: Setting Redis Connection Environment Variables (bash) DESCRIPTION: Exports environment variables containing the host, port, and password for the Upstash Redis database connection. These variables are used by the application to configure the Celery connection URL. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/celery.mdx#_snippet_1 LANGUAGE: bash CODE: ``` export UPSTASH_REDIS_HOST= export UPSTASH_REDIS_PORT= export UPSTASH_REDIS_PASSWORD= ``` ---------------------------------------- TITLE: Setting JSON Value (TypeScript) DESCRIPTION: This snippet demonstrates the basic usage of the redis.json.set command in TypeScript to set a JSON value at a specified path within a key. It requires the key, path, and the value to be set. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/set.mdx#_snippet_0 LANGUAGE: ts CODE: ``` redis.json.set(key, "$.path", value); ``` ---------------------------------------- TITLE: Popping Multiple Elements with LPOP (Python) DESCRIPTION: This snippet illustrates using the `LPOP` command with the optional `count` parameter in Python to pop multiple elements from a Redis list. After populating the list with `RPUSH`, it calls `LPOP` with the key and a count of 2, verifying that the returned value is a list containing the first two elements that were pushed. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/lpop.mdx#_snippet_1 LANGUAGE: python CODE: ``` redis.rpush("mylist", "one", "two", "three") assert redis.lpop("mylist", 2) == ["one", "two"] ``` ---------------------------------------- TITLE: Parsing REDIS_URL Environment Variable (Elixir) DESCRIPTION: Defines Elixir code within the `start` function of `application.ex` to read the `REDIS_URL` environment variable. It uses a regular expression to extract the password, host, and port from the URL string for configuring the Redis connection. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/elixir.mdx#_snippet_2 LANGUAGE: Elixir CODE: ``` def start(_type, _args) do [_, password, host, port] = Regex.run( ~r{(.+):(.+)@(.+):(\d+)}, System.get_env("REDIS_URL"), capture: :all_but_first ) port = elem(Integer.parse(port), 0) # ... end ``` ---------------------------------------- TITLE: Removing Multiple Members from Redis Sorted Set (TypeScript) DESCRIPTION: Uses the `zrem` command with a TypeScript Redis client to remove multiple specified members from the sorted set identified by the key. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zrem.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.zrem("key", "member1", "member2"); ``` ---------------------------------------- TITLE: Serverless Framework Configuration YAML DESCRIPTION: Defines the `serverless.yml` file, which configures the AWS Lambda function. It specifies the service name, runtime, environment variables (including the Redis URL), function handler, and event triggers (an HTTP GET request to `/query`). SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/auto_complete_with_serverless_redis.mdx#_snippet_7 LANGUAGE: yaml CODE: ``` service: auto-complete-api # add this if you set REDIS_URL in .env useDotenv: true frameworkVersion: "2" provider: name: aws runtime: nodejs14.x lambdaHashingVersion: 20201221 environment: REDIS_URL: REPLACE_YOUR_REDIS_URL functions: query: handler: handler.query events: - httpApi: path: /query method: get cors: true ``` ---------------------------------------- TITLE: Removing Sorted Set Members by Rank (Python) DESCRIPTION: This snippet demonstrates how to use a Python Redis client to remove elements from a sorted set between the specified ranks. It calls the zremrangebyrank method on a presumed Redis connection object, providing the sorted set key and the inclusive minimum and maximum ranks. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zremrangebyrank.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zremrangebyrank("key", 4, 20) ``` ---------------------------------------- TITLE: Configuring Serverless Project YAML DESCRIPTION: This `serverless.yml` file configures the AWS Lambda functions using the Serverless Framework. It specifies the provider (AWS, Node.js 12.x runtime), sets an environment variable (`REDIS_URL`) for the Redis connection string, and defines two functions (`record` and `get`) with their respective handler files (`handler.js`) and associated HTTP API endpoints. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/histogram.mdx#_snippet_3 LANGUAGE: yaml CODE: ``` service: histogram-api frameworkVersion: "2" provider: name: aws runtime: nodejs12.x lambdaHashingVersion: 20201221 environment: REDIS_URL: REPLACE_YOUR_URL_HERE functions: record: handler: handler.record events: - httpApi: path: /record method: post cors: true get: handler: handler.get events: - httpApi: path: /get method: get cors: true ``` ---------------------------------------- TITLE: Executing Redis SMOVE Command in Python DESCRIPTION: This Python snippet demonstrates using a Redis client library to perform the SMOVE operation. It first populates two sets, then moves a specific member from the source set to the destination set, and finally verifies the state of both sets using assertions. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/smove.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.sadd("src", "one", "two", "three") redis.sadd("dest", "four") assert redis.smove("src", "dest", "three") == True assert redis.smembers("source") == {"one", "two"} assert redis.smembers("destination") == {"three", "four"} ``` ---------------------------------------- TITLE: Demonstrating SDIFF command using Upstash Redis in TypeScript DESCRIPTION: This snippet demonstrates how to use the SDIFF command via the Upstash Redis client in TypeScript. It first adds members to two sets ('set1' and 'set2') using `sadd`, then calculates the difference between 'set1' and 'set2' using `sdiff`, and finally prints the resulting set members. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/sdiff.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); const diff = await redis.sdiff("set1", "set2"); console.log(diff); // ["a", "b"] ``` ---------------------------------------- TITLE: Setting Azure Function App Settings - Shell DESCRIPTION: This Azure CLI command configures application settings for the Function App. It sets the `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` environment variables, which are used by the Function code to connect to the Upstash Redis database. Replace ``, ``, and ``. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/azure-functions.mdx#_snippet_8 LANGUAGE: shell CODE: ``` az functionapp config appsettings set --name --resource-group AzureFunctionsQuickstart-rg --settings UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Performing SUNION with Redis - Python DESCRIPTION: This snippet demonstrates how to use the Redis SUNION command in Python. It first adds members to two separate sets ('key1' and 'key2') using the `sadd` command. Then, it performs the union operation on these two sets using `sunion` and asserts that the resulting set contains all unique members from both input sets. This requires a Redis client library like `redis-py`. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/sunion.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.sadd("key1", "a", "b", "c") redis.sadd("key2", "c", "d", "e") assert redis.sunion("key1", "key2") == {"a", "b", "c", "d", "e"} ``` ---------------------------------------- TITLE: Executing SUNION with Upstash Redis Client (TypeScript) DESCRIPTION: This snippet demonstrates how to use the Upstash Redis client to perform a SUNION operation. It first adds members to two separate sets ('set1' and 'set2') and then calls the 'sunion' method with the keys of these sets. Finally, it logs the resulting union set. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/sunion.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); const union = await redis.sunion("set1", "set2"); console.log(union); // ["a", "b", "c", "d", "e"] ``` ---------------------------------------- TITLE: Applying Weights to ZUNIONSTORE in Python DESCRIPTION: This snippet demonstrates how to apply weights to the sorted sets during a zunionstore operation in Python. It unions two sets (key1 and key2) with common members. The weights=[2, 3] option specifies multipliers for the scores of key1 and key2 respectively before aggregation. The final score for a member is the sum of its weighted scores. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zunionstore.mdx#_snippet_2 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zunionstore(["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == [("a", 5)] ``` ---------------------------------------- TITLE: Clearing JSON Data using redis.json.clear (TypeScript) DESCRIPTION: Demonstrates calling the `redis.json.clear` function on a Redis client object to clear values within a JSON document stored at a specified key. The first example clears the entire document (default path '$'), while the second clears values at a specific path. It requires a Redis client library configured to interact with a Redis instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/clear.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.json.clear("key"); ``` LANGUAGE: ts CODE: ``` await redis.json.clear("key", "$.my.key"); ``` ---------------------------------------- TITLE: Demonstrating DECRBY Command Usage with Upstash Redis - TypeScript DESCRIPTION: This snippet demonstrates how to use the DECRBY command with an Upstash Redis client. It first sets a key to an initial integer value using `set`, then calls `decrby` to decrement the value by a specified amount, showing the resulting value after the operation. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/decrby.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.set("key", 6); await redis.decrby("key", 4); // returns 2 ``` ---------------------------------------- TITLE: Setting JSON Value (Basic) - Python DESCRIPTION: Demonstrates the basic usage of the json.set command in Python to set a value at a specific path within a JSON key. Requires the key, path, and value variables to be defined. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/set.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.json.set(key, "$.path", value) ``` ---------------------------------------- TITLE: Configuring Laravel Cache Driver in .env DESCRIPTION: These .env variables configure Laravel to use 'redis' as the primary cache store. The REDIS_CACHE_DB specifies which Redis database index (usually 0) should be used specifically for caching. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/laravel.mdx#_snippet_5 LANGUAGE: .env CODE: ``` CACHE_STORE="redis" REDIS_CACHE_DB="0" ``` ---------------------------------------- TITLE: Scanning Redis Set Members with SSCAN (TypeScript) DESCRIPTION: Demonstrates how to use the SSCAN command to incrementally iterate through members of a Redis set. It first adds initial members to a set using SADDBefore scanning. Then, it calls SSCAN with a cursor (starting at 0) and a MATCH pattern to filter results. The output includes the next cursor and the array of matched members. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/sscan.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.sadd("key", "a", "ab","b", "c"); const [newCursor, fields] = await redis.sscan("key", 0, { match: "a*"}); console.log(newCursor); // likely `0` since this is a very small set console.log(fields); // ["a", "ab"] ``` ---------------------------------------- TITLE: Initializing Multi Regional Fixed Window Ratelimit (TypeScript) DESCRIPTION: Initializes a MultiRegionRatelimit instance for a multi-regional setup using the fixedWindow algorithm. It requires an array of Redis instances and configures the limiter to allow 10 requests per 10 seconds across the specified regions. Requires the `@upstash/ratelimit` and `@upstash/redis` libraries. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/algorithms.mdx#_snippet_1 LANGUAGE: typescript CODE: ``` const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }) ], limiter: MultiRegionRatelimit.fixedWindow(10, "10 s"), }); ``` ---------------------------------------- TITLE: Adding Entry to Redis Stream (TypeScript) DESCRIPTION: Appends a single new entry to a Redis stream. It uses '*' as the ID to automatically generate a unique ID for the new entry. The data is provided as a key-value object. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/stream/xadd.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.xadd(key, "*", { name: "John Doe", age: 30 }); ``` ---------------------------------------- TITLE: Deleting Multiple Keys Upstash Redis Python DESCRIPTION: This snippet demonstrates how to use the `delete` method (corresponding to the Redis DEL command) to remove multiple keys. It first sets two example keys, then calls `delete` with both key names, and finally asserts that the keys have been successfully removed by checking their values using the `get` method, which should return None. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/del.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.set("key1", "Hello") redis.set("key2", "World") redis.delete("key1", "key2") assert redis.get("key1") is None assert redis.get("key2") is None ``` ---------------------------------------- TITLE: Removing a Single Member from Redis Sorted Set (TypeScript) DESCRIPTION: Uses the `zrem` command with a TypeScript Redis client to remove a single specified member from the sorted set identified by the key. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zrem.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.zrem("key", "member"); ``` ---------------------------------------- TITLE: Setting Key Expiry (PEXPIREAT) - Python DESCRIPTION: This Python snippet demonstrates how to set an expiration timestamp for a Redis key using the `pexpireat` command via a Python client. It illustrates two methods: using a Unix timestamp in milliseconds (calculated from the current time) and using a `datetime` object representing a future point in time. The code first sets a value for the key "mykey" and then applies the expiration. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/pexpireat.mdx#_snippet_0 LANGUAGE: py CODE: ``` # With a unix timestamp redis.set("mykey", "Hello") redis.pexpireat("mykey", int(time.time() * 1000) ) # With a datetime object redis.set("mykey", "Hello") redis.pexpireat("mykey", datetime.datetime.now() + datetime.timedelta(seconds=5)) ``` ---------------------------------------- TITLE: Appending Basic Entry (Python) DESCRIPTION: This snippet demonstrates appending a new entry to a Redis stream using the `xadd` command in Python. It automatically generates an entry ID (`*`) and includes a simple key-value map for the entry data. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/stream/xadd.mdx#_snippet_0 LANGUAGE: py CODE: ``` redis.xadd(key, "*", { "name": "John Doe", "age": 30 }) ``` ---------------------------------------- TITLE: Counting Sorted Set Elements with ZCOUNT (TypeScript) DESCRIPTION: This snippet demonstrates adding members to a Redis sorted set using ZADD and then counting members within a score range using ZCOUNT. It shows how to specify exclusive minimums (e.g., '(1') and inclusive or unbounded maximums (e.g., '+inf'). The example uses an assumed 'redis' client object and logs the resulting count. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zcount.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" } ); const elements = await redis.zcount("key", "(1", "+inf"); console.log(elements); // 1 ``` ---------------------------------------- TITLE: Using Laravel Cache Functions with Redis PHP DESCRIPTION: This PHP snippet shows how to use Laravel's standard Cache functions to store and retrieve data. With the CACHE_STORE set to 'redis', these operations will automatically utilize the configured Upstash Redis instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/laravel.mdx#_snippet_6 LANGUAGE: php CODE: ``` Cache::put('key', 'value', now()->addMinutes(10)); $value = Cache::get('key'); ``` ---------------------------------------- TITLE: Retrieving JSON Value with Options (TypeScript) DESCRIPTION: Retrieves a value from a JSON document stored in Redis, applying formatting options for indentation, newlines, and spaces in the output JSON string. Uses the `redis.json.get` method with an options object containing `indent`, `newline`, and `space` properties. Requires a connected Redis client instance (`redis`). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/get.mdx#_snippet_1 LANGUAGE: ts CODE: ``` const value = await redis.json.get("key", { indent: " ", newline: "\n", space: " ", }, "$.path.to.somewhere"); ``` ---------------------------------------- TITLE: Executing MSETNX with TypeScript DESCRIPTION: Demonstrates how to use the Redis MSETNX command with a TypeScript client. It shows how to pass an object containing key-value pairs to be set atomically, provided none of the keys already exist. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/msetnx.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` redis.msetnx({ "key1": "value1", "key2": "value2" }) ``` ---------------------------------------- TITLE: Setting a Key Only If Exists TypeScript DESCRIPTION: Illustrates how to use the `set` command with the `xx` option to conditionally set a key. The key "my-key" will only be updated with the new value if it already exists in the database. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/set.mdx#_snippet_2 LANGUAGE: ts CODE: ``` await redis.set("my-key", {my: "value"}, { xx: true }); ``` ---------------------------------------- TITLE: Initializing Upstash Redis with isomorphic-fetch Polyfill (TypeScript) DESCRIPTION: Demonstrates how to correctly initialize the `@upstash/redis` client in environments requiring a `fetch` polyfill. It shows importing both the `Redis` client and `isomorphic-fetch` to ensure the necessary API is available before instantiating the client. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/troubleshooting.mdx#_snippet_1 LANGUAGE: typescript CODE: ``` import { Redis } from "@upstash/redis"; import "isomorphic-fetch"; const redis = new Redis({ /*...*/ }); ``` ---------------------------------------- TITLE: Weighted ZINTER with Scores Redis Python DESCRIPTION: Shows how to apply weights to sorted sets during a ZINTER operation in Python. It adds elements to two sets, specifies weights for each set (2 for key1, 3 for key2), performs the weighted intersection with scores and sum aggregation, and verifies the resulting score for the common member 'a'. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zinter.mdx#_snippet_2 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1}) redis.zadd("key2", {"a": 1}) result = redis.zinter(["key1", "key2"], withscores=True, aggregate="SUM", weights=[2, 3]) assert result == [("a", 5)] ``` ---------------------------------------- TITLE: Configuring Local Fastly Backend for Upstash Redis (TOML) DESCRIPTION: This snippet shows how to add a backend configuration for Upstash Redis to the fastly.toml file's [local_server.backends] section. This configuration is necessary to allow the fastly compute serve command to correctly proxy requests from the local development server to the actual Upstash Redis endpoint. It requires the UPSTASH_REDIS_REST_URL. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/fastlycompute.mdx#_snippet_1 LANGUAGE: TOML CODE: ``` [local_server.backends.upstash] url = "UPSTASH_REDIS_REST_URL" ``` ---------------------------------------- TITLE: Using ZINCRBY with Python Redis Client DESCRIPTION: This snippet demonstrates how to use the ZINCRBY command with a Python Redis client. It first adds initial members and scores to a sorted set named 'myset' using ZADD, and then increments the score of the member 'one' by 2 using ZINCRBY, asserting the expected new score. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zincrby.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) assert redis.zincrby("myset", 2, "one") == 3 ``` ---------------------------------------- TITLE: Initializing Sliding Window Ratelimit with Blocking in Python DESCRIPTION: This snippet demonstrates how to initialize an Upstash rate limiter using the Sliding Window algorithm and the `block_until_ready` method. It attempts to perform an action, blocking execution for up to 30 seconds if the rate limit is currently exceeded, waiting for the next window. It requires the `upstash_ratelimit` and `upstash_redis` libraries. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-py/features.mdx#_snippet_0 LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, SlidingWindow from upstash_redis import Redis # Create a new ratelimiter, that allows 10 requests per 10 seconds ratelimit = Ratelimit( redis=Redis.from_env(), limiter=SlidingWindow(max_requests=10, window=10), ) response = ratelimit.block_until_ready("id", timeout=30) if not response.allowed: print("Unable to process, even after 30 seconds") elif response.allowed: # do_expensive_calculation() print("Here you go!") ``` ---------------------------------------- TITLE: Adding Dependencies to requirements.txt (txt) DESCRIPTION: This snippet shows the required content for the `requirements.txt` file located in the Lambda function's source directory (`/hello_world/`). It lists the Python packages needed for the function to execute, specifically including `requests` and `upstash-redis`. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/using_aws_sam.mdx#_snippet_2 LANGUAGE: txt CODE: ``` requests upstash-redis ``` ---------------------------------------- TITLE: Popping Single Element with RPOP (TypeScript) DESCRIPTION: Demonstrates how to use `redis.rpop` without the count argument to remove and return the last element of a list. It first pushes elements using `rpush` and then pops one, logging the result. Expects a single string value as output. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/rpop.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.rpush("key", "a", "b", "c"); const element = await redis.rpop("key"); console.log(element); // "c" ``` ---------------------------------------- TITLE: Removing Members from a Redis Set using SREM in TypeScript DESCRIPTION: This TypeScript code snippet demonstrates how to use the `srem` command with an Upstash Redis client. It first adds members to a set using `sadd` and then removes specified members using `srem`, showing how the command returns the count of members that were successfully removed. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/srem.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.sadd("set", "a", "b", "c"); const removed = await redis.srem("set", "a", "b", "d"); console.log(removed); // 2 ``` ---------------------------------------- TITLE: Deleting Fields using redis.hdel in TypeScript DESCRIPTION: Demonstrates how to use the `hdel` method of the `@upstash/redis` client to delete specific fields from a hash key. Requires a `redis` client instance. The method takes the key and one or more field names as arguments and returns the number of fields successfully removed. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hdel.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.hdel(key, 'field1', 'field2'); // returns 5 ``` ---------------------------------------- TITLE: Incrementing Redis Hash Field with HINCRBY in Python DESCRIPTION: This snippet demonstrates how to use the Redis HINCRBY command in Python. It shows how to set an initial value for a hash field using HSET and then increment that value using HINCRBY, asserting the correct result. This requires a Python Redis client library. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hincrby.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.hset("myhash", "field1", 5) assert redis.hincrby("myhash", "field1", 10) == 15 ``` ---------------------------------------- TITLE: Configuring Upstash Redis Environment Variables DESCRIPTION: Sets the connection URL (`UPSTASH_REDIS_REST_URL`) and token (`UPSTASH_REDIS_REST_TOKEN`) for your Upstash Redis database in the project's `.env` file. Replace the placeholder values with your actual credentials. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/ion.mdx#_snippet_3 LANGUAGE: .env CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Define AWS CDK Counter Stack TypeScript DESCRIPTION: Defines an AWS CDK stack that provisions the necessary AWS resources. It creates a Node.js Lambda function from the `api/counter.ts` file, configures its runtime, handler, environment variables (for Upstash credentials), and sets up a public Function URL endpoint. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/aws-lambda.mdx#_snippet_4 LANGUAGE: typescript CODE: ``` import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as nodejs from 'aws-cdk-lib/aws-lambda-nodejs'; export class CounterCdkStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const counterFunction = new nodejs.NodejsFunction(this, 'CounterFunction', { entry: 'api/counter.ts', handler: 'handler', runtime: lambda.Runtime.NODEJS_20_X, environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || '', UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || '', }, bundling: { format: nodejs.OutputFormat.ESM, target: "node20", nodeModules: ['@upstash/redis'], }, }); const counterFunctionUrl = counterFunction.addFunctionUrl({ authType: lambda.FunctionUrlAuthType.NONE, }); new cdk.CfnOutput(this, "counterFunctionUrlOutput", { value: counterFunctionUrl.url, }) } } ``` ---------------------------------------- TITLE: Setting Hash Field If Not Exists in Redis (TypeScript) DESCRIPTION: This snippet demonstrates using a TypeScript client (likely Upstash Redis based on context) to execute the HSETNX command. It attempts to set the field 'id' with the value 1 in the hash 'key', but only if 'id' does not already exist in 'key'. The result is an integer (1 if set, 0 if not). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hsetnx.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.hsetnx("key", "id", 1) ``` ---------------------------------------- TITLE: Configure Upstash Redis Environment Variables DESCRIPTION: Defines environment variables in a .env file used by the Python application to connect to the Upstash Redis database. Requires host, port, and password. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_realtime_chat.mdx#_snippet_1 LANGUAGE: bash CODE: ``` UPSTASH_REDIS_HOST=your_upstash_redis_host UPSTASH_REDIS_PORT=your_upstash_redis_port UPSTASH_REDIS_PASSWORD=your_upstash_redis_password ``` ---------------------------------------- TITLE: Executing ZREMRANGEBYRANK with TypeScript Redis Client DESCRIPTION: Shows how to invoke the zremrangebyrank method on a Redis client instance in TypeScript. This command removes all members from the specified sorted set (identified by 'key') whose rank is between 'min' (inclusive) and 'max' (inclusive. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zremrangebyrank.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.zremrangebyrank("key", 4, 20) ``` ---------------------------------------- TITLE: Decrementing Redis Key using TypeScript DESCRIPTION: This snippet demonstrates how to decrement the integer value of a Redis key using a TypeScript client library. It first sets a key named 'key' to the integer value 6, then calls the 'decr' method on the same key. The expected output after the decrement is 5. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/decr.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.set("key", 6); await redis.decr("key"); // returns 5 ``` ---------------------------------------- TITLE: Getting Set Cardinality with SCARD in TypeScript DESCRIPTION: This example shows how to get the number of elements in a Redis set using the SCARD command in a TypeScript environment. It first adds three members ('a', 'b', 'c') to a set named 'key' using SADD, then retrieves the cardinality of the set using SCARD, and finally logs the resulting count (which will be 3). This assumes you have an initialized Redis client instance available. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/scard.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.sadd("key", "a", "b", "c"); const cardinality = await redis.scard("key"); console.log(cardinality); // 3 ``` ---------------------------------------- TITLE: Installing FastAPI, Upstash Redis Client, and Rate Limiter (Shell) DESCRIPTION: This shell command installs the required Python packages to build the FastAPI application with Upstash Redis rate limiting. It includes `fastapi` for the web framework, `upstash-redis` for connecting to Redis, `upstash-ratelimit` for the rate limiting logic, and `uvicorn[standard]` as the ASGI server. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_rate_limiting.mdx#_snippet_0 LANGUAGE: shell CODE: ``` pip install fastapi upstash-redis upstash-ratelimit uvicorn[standard] ``` ---------------------------------------- TITLE: Retrieving List Range using Redis LRANGE (Python) DESCRIPTION: This snippet demonstrates how to use the Redis LRANGE command in Python. It first populates a list using RPUSH and then retrieves sub-ranges using LRANGE with both positive (0, 1) and negative (0, -1) indices, verifying the results using assertions. Requires a connected Redis client instance named `redis`. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/lrange.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.rpush("mylist", "one", "two", "three") assert redis.lrange("mylist", 0, 1) == ["one", "two"] assert redis.lrange("mylist", 0, -1) == ["one", "two", "three"] ``` ---------------------------------------- TITLE: Removing Members from Redis Set (Python) DESCRIPTION: This Python example demonstrates the usage of the Redis SREM command. It first adds multiple members ('one', 'two', 'three') to a set named 'myset' using the SADD command, and then attempts to remove 'one' and 'four' using SREM, asserting that only 1 member was successfully removed (since 'four' was not in the set). This requires a Python Redis client library installed. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/srem.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.sadd("myset", "one", "two", "three") assert redis.srem("myset", "one", "four") == 1 ``` ---------------------------------------- TITLE: Executing Redis FLUSHDB Synchronously in Python DESCRIPTION: This snippet demonstrates how to perform the Redis FLUSHDB operation synchronously using a Python client. Executing this command deletes all keys in the current database immediately. Use this command with extreme caution as data loss is permanent and irreversible. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/server/flushdb.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.flushall() ``` ---------------------------------------- TITLE: Initializing Token Bucket Ratelimiter with Upstash Ratelimit Python DESCRIPTION: This code snippet illustrates the initialization of a Ratelimit object configured with the TokenBucket algorithm from `upstash-ratelimit`. It connects to Redis and defines the bucket's capacity (`max_tokens`), the rate at which tokens are added (`refill_rate`), and the time interval in seconds for the refill process (`interval`). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-py/algorithms.mdx#_snippet_3 LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, TokenBucket from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=TokenBucket(max_tokens=10, refill_rate=5, interval=10), ) ``` ---------------------------------------- TITLE: Checking Multiple Set Members using SMISMEMBER in Python DESCRIPTION: This snippet demonstrates the usage of the Redis SMISMEMBER command in Python. It first adds members to a set named "myset" using SADD, and then uses SMISMEMBER to check for the existence of multiple members, asserting the expected boolean list results. It requires a Redis client library like `redis-py` connected to a Redis instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/smismember.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.sadd("myset", "one", "two", "three") assert redis.smismember("myset", "one", "four") == [True, False] assert redis.smismember("myset", "four", "five") == [False, False] ``` ---------------------------------------- TITLE: Setting Multiple Fields in Redis Hash using Python HSET DESCRIPTION: This Python snippet demonstrates how to use a Redis client library's `hset` method to set multiple fields within a hash. It shows setting 'field1' and 'field2' in the hash 'myhash' and asserts the expected return value (2, the number of fields set). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hmset.mdx#_snippet_0 LANGUAGE: python CODE: ``` # Set multiple fields assert redis.hset("myhash"{ "field1": "Hello", "field2": "World" }) == 2 ``` ---------------------------------------- TITLE: Getting Redis List Length with LLEN - TypeScript DESCRIPTION: Demonstrates how to add elements to a Redis list using `rpush` and then retrieve its length using `llen` with the Upstash Redis client in TypeScript. It shows creating a list with three elements and then logging the resulting length (3). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/llen.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.rpush("key", "a", "b", "c"); const length = await redis.llen("key"); console.log(length); // 3 ``` ---------------------------------------- TITLE: Getting Redis List Length with LLEN Python DESCRIPTION: Demonstrates adding elements to a Redis list using RPUSH and then retrieving the list's length using the LLEN command in Python. It asserts that the length is correct after adding three elements. Requires a Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/llen.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.rpush("key", "a", "b", "c") assert redis.llen("key") == 3 ``` ---------------------------------------- TITLE: Finding Nth Element Index with LPOS Rank Python DESCRIPTION: Shows how to use the LPOS command with the 'rank' argument to find the index of the Nth occurrence of an element. It pushes 'a', 'b', 'c', 'b' to 'key', then asserts that the index of the 2nd occurrence of 'b' is 3. Requires a Redis client library. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/lpos.mdx#_snippet_1 LANGUAGE: python CODE: ``` redis.rpush("key", "a", "b", "c", "b"); assert redis.lpos("key", "b", rank=2) == 3 ``` ---------------------------------------- TITLE: Configuring SST Nextjs Component Environment in TypeScript DESCRIPTION: Configures the SST application within `sst.config.ts`, defining the app name and removal policy, and passing the Upstash Redis environment variables to the deployed Next.js component for access during runtime. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/ion.mdx#_snippet_4 LANGUAGE: typescript CODE: ``` /// export default $config({ app(input) { return { name: "my-app", removal: input?.stage === "production" ? "retain" : "remove", home: "aws", }; }, async run() { new sst.aws.Nextjs("MyWeb", { environment: { UPSTASH_REDIS_REST_URL: process.env.UPSTASH_REDIS_REST_URL || "", UPSTASH_REDIS_REST_TOKEN: process.env.UPSTASH_REDIS_REST_TOKEN || "", }, }); }, }); ``` ---------------------------------------- TITLE: Loading and Executing Redis Script with SHA1 - Python DESCRIPTION: This snippet demonstrates how to use a Python Redis client to load a simple Lua script ('return 1') into the Redis server's script cache using `redis.script_load`. It then shows how to retrieve the script's SHA1 hash and execute the cached script efficiently using `redis.evalsha` with the obtained hash. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/scripts/script_load.mdx#_snippet_0 LANGUAGE: python CODE: ``` sha1 = redis.script_load("return 1") assert redis.evalsha(sha1) == 1 ``` ---------------------------------------- TITLE: Checking Multiple Keys Existence using EXISTS in TypeScript DESCRIPTION: This snippet demonstrates setting two keys in Redis and then checking the existence of three keys (two existing, one non-existing) using the `exists` command. It shows that the command returns an integer representing the count of existing keys among those queried. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/exists.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.set("key1", "value1") await redis.set("key2", "value2") const keys = await redis.exists("key1", "key2", "key3"); console.log(keys) // 2 ``` ---------------------------------------- TITLE: Checking Member Existence in Redis Set - TypeScript DESCRIPTION: This snippet demonstrates how to use a Redis client in TypeScript to check if a specific member exists within a set. It first adds members to a set using `sadd` and then uses `sismember` with the set key and the member to check, printing the result (1 for true, 0 for false). Requires a configured Redis client instance (`redis`). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/sismember.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.sadd("set", "a", "b", "c"); const isMember = await redis.sismember("set", "a"); console.log(isMember); // 1 ``` ---------------------------------------- TITLE: Retrieving Multiple Hash Fields using Python DESCRIPTION: This snippet demonstrates how to use the `hmget` command in Python to retrieve specific fields from a Redis hash. It first uses `hset` to populate the hash `myhash` and then asserts that `hmget` correctly returns the values for `field1` and `field2`. This requires a connected Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hmget.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hmget("myhash", "field1", "field2") == ["Hello", "World"] ``` ---------------------------------------- TITLE: Retrieving ZRANGE by Rank (TypeScript) DESCRIPTION: This snippet demonstrates retrieving elements from a sorted set using ZRANGE by rank. It first adds two members with scores, then calls zrange with a start rank of 1 and end rank of 3, which retrieves elements based on their order in the sorted set. The expected output is an array containing "m2". SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zrange.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, ) const res = await redis.zrange("key", 1, 3) console.log(res) // ["m2"] ``` ---------------------------------------- TITLE: Example Usage of HINCRBYFLOAT in Python DESCRIPTION: This snippet demonstrates how to use the HINCRBYFLOAT command in Python. It first sets a hash field 'field1' in the 'myhash' key to an initial float value (5.5) using 'hset', and then increments it by a specified float value (10.1) using 'hincrbyfloat'. Finally, it asserts that the resulting value is close to the expected sum (15.6), accounting for potential floating-point inaccuracies. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hincrbyfloat.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.hset("myhash", "field1", 5.5) assert redis.hincrbyfloat("myhash", "field1", 10.1) - 15.6 < 0.0001 ``` ---------------------------------------- TITLE: Installing Python Dependencies with pip DESCRIPTION: Installs the required Python packages for the web scraper. This includes `threading` (for multithreading), `requests` (for HTTP requests), `upstash-redis` (for Redis client), and `python-dotenv` (for loading environment variables). SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_multithreading.mdx#_snippet_1 LANGUAGE: bash CODE: ``` pip install threading requests upstash-redis python-dotenv ``` ---------------------------------------- TITLE: Defining Project Dependencies in package.json (JSON) DESCRIPTION: This JSON snippet defines the project's required dependencies in the package.json file. It specifies the latest versions of the '@upstash/ratelimit' and '@upstash/redis' libraries, which are essential for implementing the rate limiting logic. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/rate-limiting.mdx#_snippet_2 LANGUAGE: json CODE: ``` { "dependencies": { "@upstash/ratelimit": "latest", "@upstash/redis": "latest" } } ``` ---------------------------------------- TITLE: Searching JSON Array Index in Redis (Python) DESCRIPTION: This Python snippet demonstrates how to use the `json.arrindex` method from a Redis client library to find the first index of a specific value ('a') within a JSON array located at the path `$.path.to.array` inside the key `key`. The result, the index of the first occurrence or -1 if not found, is stored in the `index` variable. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/arrindex.mdx#_snippet_0 LANGUAGE: python CODE: ``` index = redis.json.arrindex("key", "$.path.to.array", "a") ``` ---------------------------------------- TITLE: Demonstrating Default Base64 Encoded Response (TypeScript) DESCRIPTION: Shows a basic example of setting and getting data using the `@upstash/redis` client. It illustrates the client's default behavior of returning response values as base64 encoded strings (`dmFsdWU=` in the example) to prevent potential deserialization issues. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/troubleshooting.mdx#_snippet_2 LANGUAGE: typescript CODE: ``` await redis.set("key", "value"); const data = await redis.get("key"); console.log(data); // dmFsdWU= ``` ---------------------------------------- TITLE: Adding Elements and Counting Sorted Set Size (TypeScript) DESCRIPTION: This snippet demonstrates adding two members ("one", "two") with scores to a Redis sorted set named "key" using the `zadd` command. It then attempts to retrieve information using the `zrank` command and logs the result, which is shown as `2`. Although `zrank` is used, the expected output `// 2` corresponds to the number of elements, suggesting it might illustrate the result of a `ZCARD` operation. Requires a Redis client library for TypeScript. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zcard.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" }, ); const elements = await redis.zrank("key"); console.log(elements); // 2 ``` ---------------------------------------- TITLE: Initializing Multi Regional Sliding Window Ratelimit (TypeScript) DESCRIPTION: Initializes a MultiRegionRatelimit instance for a multi-regional setup using the slidingWindow algorithm. It requires an array of Redis instances and configures the limiter to allow 10 requests per 10 seconds across the specified regions. Note the potential performance warning associated with this configuration. Requires the `@upstash/ratelimit` and `@upstash/redis` libraries. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/algorithms.mdx#_snippet_4 LANGUAGE: typescript CODE: ``` const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }) ], limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"), }); ``` ---------------------------------------- TITLE: Initializing MultiRegionRatelimit with Multiple Redis Instances (TypeScript) DESCRIPTION: Shows how to create a MultiRegionRatelimit instance by providing an array of Redis client instances. This setup enables lower latency by checking the closest database and asynchronously replicating state. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/features.mdx#_snippet_5 LANGUAGE: TypeScript CODE: ``` import { MultiRegionRatelimit } from "@upstash/ratelimit"; // for deno: see above import { Redis } from "@upstash/redis"; // Create a new ratelimiter, that allows 10 requests per 10 seconds const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }), new Redis({ /* auth */ }), ], limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"), analytics: true, }); // Use a constant string to limit all requests with a single ratelimit // Or use a userID, apiKey or ip address for individual limits. const identifier = "api"; const { success } = await ratelimit.limit(identifier); ``` ---------------------------------------- TITLE: Using GETSET in Redis with Python DESCRIPTION: Demonstrates how to use the GETSET command with a Redis client in Python. It first sets a key's value and then calls GETSET to retrieve the old value while simultaneously updating the key with a new value. The assertion verifies that the correct old value is returned. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/getset.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.set("key", "old-value") assert redis.getset("key", "newvalue") == "old-value" ``` ---------------------------------------- TITLE: Using LPUSH with Redis Client - TypeScript Example DESCRIPTION: This snippet demonstrates how to use the LPUSH command with an asynchronous Redis client in TypeScript. It shows pushing multiple elements initially and then pushing a single element, illustrating how the return value is the new length of the list after each operation. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/lpush.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` const length1 = await redis.lpush("key", "a", "b", "c"); console.log(length1); // 3 const length2 = await redis.lpush("key", "d"); console.log(length2); // 4 ``` ---------------------------------------- TITLE: ZINTERSTORE with Aggregation using Python DESCRIPTION: This example demonstrates using the `zinterstore` command with the `aggregate="SUM"` option and `withscores=True`. It calculates the intersection of `key1` and `key2`, sums the scores of intersecting members (like 'a' and 'b'), and stores the result with the aggregated scores in `dest`. It asserts that the resulting set contains three elements. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zinterstore.mdx#_snippet_1 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zinterstore("dest", ["key1", "key2"], withscores=True, aggregate="SUM") assert result == 3 ``` ---------------------------------------- TITLE: Getting Key Type using Redis Client (TypeScript) DESCRIPTION: This snippet demonstrates how to determine the data type of a key stored in Redis using a TypeScript client. It first sets a string value to a key named "key" and then calls the `redis.type()` method with the same key to retrieve its type, printing the result to the console. This requires a connected Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/type.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.set("key", "value"); const t = await redis.type("key"); console.log(t) // "string" ``` ---------------------------------------- TITLE: Popping first element from Redis JSON array - Python DESCRIPTION: This snippet shows how to use `redis.json.arrpop` to remove and return the *first* element from a JSON array located at a specified path within a Redis key by explicitly providing the index 0. Requires the `redis-py` library. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/arrpop.mdx#_snippet_1 LANGUAGE: python CODE: ``` firstElement = redis.json.arrpop("key", "$.path.to.array", 0) ``` ---------------------------------------- TITLE: Calling LREM Command using TypeScript DESCRIPTION: This snippet demonstrates the usage of the Redis LREM command via a TypeScript client, likely the Upstash Redis SDK. It first initializes a list named 'key' with multiple elements using `lpush`, then calls `lrem` to remove up to 4 occurrences of the element 'b', and finally logs the returned count of removed elements. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/lrem.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.lpush("key", "a", "a", "b", "b", "c"); const removed = await redis.lrem("key", 4, "b"); console.log(removed) // 2 ``` ---------------------------------------- TITLE: Scanning Sorted Set by Pattern and Count (TypeScript) DESCRIPTION: Shows how to scan a sorted set using `sscan` with both `match` and `count` options. After populating the set, it scans from cursor 0, filtering by "a*" and limiting the results to 1 member per call. The returned cursor and matching members are logged. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zscan.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.zadd("key", { score: 1, member: "a" }, { score: 2, member: "ab" }, { score: 3, member: "b" }, { score: 4, member: "c" }, { score: 5, member: "d" }, ) const [newCursor, members] = await redis.sscan("key", 0, { match: "a*", count: 1}); console.log(newCursor); // likely `0` since this is a very small set console.log(members); // ["a"] ``` ---------------------------------------- TITLE: Executing Redis Script by SHA (EVALSHA) Python DESCRIPTION: This Python snippet demonstrates how to execute a cached Lua script on Redis using the `evalsha` command via a Redis client instance. It calls `redis.evalsha` with a specific SHA1 hash representing the cached script and a list of arguments to be passed to that script, then asserts the expected return value. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/scripts/evalsha.mdx#_snippet_0 LANGUAGE: python CODE: ``` result = redis.evalsha("fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb", args=["hello"]) assert result = "hello" ``` ---------------------------------------- TITLE: Chaining commands in Redis pipelines in Python DESCRIPTION: Shows an alternative syntax for building Redis pipelines by chaining command methods directly onto the pipeline object. This provides a more concise way to add multiple commands to the pipeline before executing them with `exec()`. Requires an initialized `redis` client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/features.mdx#_snippet_4 LANGUAGE: python CODE: ``` pipeline = redis.pipeline() pipeline.set("foo", 1).incr("foo").get("foo") result = pipeline.exec() print(result) # prints [True, 2, '2'] ``` ---------------------------------------- TITLE: Adding Elements with RPUSH and Verifying with LRANGE (Python) DESCRIPTION: This Python snippet demonstrates using the `redis.rpush` method to add multiple elements ('one', 'two', 'three') to a Redis list named 'mylist' and asserts that the operation returns the new length (3). It then uses the `lrange` command to retrieve the entire list from index 0 to -1 and asserts that the retrieved list matches the elements pushed, confirming the order and content. Requires a connected Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/rpush.mdx#_snippet_0 LANGUAGE: python CODE: ``` assert redis.rpush("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["one", "two", "three"] ``` ---------------------------------------- TITLE: Checking Hash Length in Redis Python DESCRIPTION: This snippet demonstrates how to use the `hlen` method in a Redis Python client to get the number of fields in a hash. It shows retrieving the length of an empty hash and then the length after adding fields, using assertions to verify the results. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hlen.mdx#_snippet_0 LANGUAGE: python CODE: ``` assert redis.hlen("myhash") == 0 redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hlen("myhash") == 2 ``` ---------------------------------------- TITLE: Install ioredis Client DESCRIPTION: Installs the `ioredis` package, a robust and performant Redis client for Node.js, which is used to interact with the Upstash database. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/auto_complete_with_serverless_redis.mdx#_snippet_3 LANGUAGE: shell CODE: ``` npm install ioredis ``` ---------------------------------------- TITLE: Installing Redis Client - Bash DESCRIPTION: This command uses npm to install the @upstash/redis package, which is required to interact with the Upstash Redis database from the Nuxt application. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/nuxtjs_with_redis.mdx#_snippet_1 LANGUAGE: bash CODE: ``` npm install @upstash/redis ``` ---------------------------------------- TITLE: Using ZPOPMAX in Python DESCRIPTION: This Python code snippet demonstrates how to interact with a Redis sorted set using a Python client. It first adds multiple members with scores to a sorted set named 'myset' using `zadd`, then uses `zpopmax` to remove and return the member with the highest score (defaulting to popping one element when count is not specified), and finally uses an assertion to verify the correctness of the returned value. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zpopmax.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zpopmax("myset") == [("c", 3)] ``` ---------------------------------------- TITLE: Setting Expiration on Redis Hash Field using TypeScript DESCRIPTION: This snippet demonstrates setting a hash field using `hset` and then applying an expiration time of 1 second to that specific field using `hexpire`. It shows the expected return value (1) indicating successful expiration setting. This requires a Redis client library (like `@upstash/redis` or similar) configured and connected. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hexpire.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.hset("my-key", "my-field", "my-value"); const expirationSet = await redis.hexpire("my-key", "my-field", 1); console.log(expirationSet); // 1 ``` ---------------------------------------- TITLE: Moving Element Between Redis Lists (TypeScript) DESCRIPTION: This snippet demonstrates pushing elements onto a source list using `rpush` and then moving an element from the left side of the source list to the left side of a destination list using the Redis `move` command (client method for LMOVE). It shows how to use the `source`, `destination`, `from`, and `to` parameters. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/lmove.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.rpush("source", "a", "b", "c"); const element = await redis.move("source", "destination", "left", "left"); ``` ---------------------------------------- TITLE: Adding Entry with Trimming to Redis Stream (TypeScript) DESCRIPTION: Appends a single new entry to a Redis stream and applies trimming based on specified criteria (e.g., MAXLEN or MINID) to control the stream size. The options object includes the trim type, threshold, comparison operator, and an optional limit. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/stream/xadd.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.xadd(key, "*", { name: "John Doe", age: 30 }, { trim: { type: "MAXLEN", threshold: 1000, comparison: "=", } }); ``` ---------------------------------------- TITLE: Implementing Google Cloud Function with Redis Client (JavaScript) DESCRIPTION: This snippet defines a Google Cloud Function `helloGET` that initializes a Redis client using `ioredis` and connects to an Upstash Redis database. It increments a counter key named "counter" in Redis upon each HTTP request and sends the updated count as the response. Requires replacing placeholders with actual Redis connection details and depends on the `ioredis` NPM package. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/getstartedgooglecloudfunctions.mdx#_snippet_0 LANGUAGE: javascript CODE: ``` var Redis = require("ioredis"); if (typeof client === "undefined") { var client = new Redis("rediss://:YOUR_PASSWORD@YOUR_ENDPOINT:YOUR_PORT"); } exports.helloGET = async (req, res) => { let count = await client.incr("counter"); res.send("Page view:" + count); }; ``` ---------------------------------------- TITLE: Getting a Single Random Member (Python) DESCRIPTION: This snippet demonstrates how to use the `srandmember` command to retrieve a single random member from a Redis set using the Python client. It adds initial members to the set and then calls `srandmember` without the count parameter, asserting that the result is one of the expected set members. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/srandmember.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.sadd("myset", "one", "two", "three") assert redis.srandmember("myset") in {"one", "two", "three"} ``` ---------------------------------------- TITLE: Using PTTL with Set, Expire, and Persist in Python DESCRIPTION: This snippet demonstrates the behavior of the Redis PTTL command in Python. It first sets a key, showing PTTL returns -1 for a key with no expiration. Then it sets an expiration, showing PTTL returns a positive value. Finally, it persists the key, showing PTTL returns -1 again. Assertions are used to verify the expected output at each stage. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/pttl.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.set("key1", "Hello") assert redis.pttl("key1") == -1 redis.expire("key1", 1000) assert redis.pttl("key1") > 0 redis.persist("key1") assert redis.pttl("key1") == -1 ``` ---------------------------------------- TITLE: Querying Sorted Set Range Reversed in Python DESCRIPTION: Illustrates how to fetch a range of elements from a Redis sorted set in reverse order using the `rev=True` parameter with ZRANGE. Requires an initialized Redis client and a sorted set with data. It adds elements and asserts the reversed range [0, 1] returns expected values. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zrange.mdx#_snippet_1 LANGUAGE: python CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrange("myset", 0, 1, rev=True) == ["c", "b"] ``` ---------------------------------------- TITLE: Executing EVALSHA_RO using Python Redis Client DESCRIPTION: This snippet demonstrates calling the `evalsha_ro` method on a Redis client object in Python. It executes a read-only Lua script identified by its SHA1 hash, passing arguments to the script. The example asserts the expected return value. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/scripts/evalsha_ro.mdx#_snippet_0 LANGUAGE: Python CODE: ``` result = redis.evalsha_ro("fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb", args=["hello"]) assert result = "hello" ``` ---------------------------------------- TITLE: Evaluating Lua Script with Keys in Upstash Redis (Python) DESCRIPTION: This snippet demonstrates how to define and evaluate a Lua script that accesses a key using the `KEYS` array within the script. It first sets a key using the Redis client and then calls `redis.eval`, passing the script and the list of keys accessed. It asserts that the result matches the key's value. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/scripts/eval.mdx#_snippet_0 LANGUAGE: python CODE: ``` script = """ local value = redis.call("GET", KEYS[1]) return value """ redis.set("mykey", "Hello") assert redis.eval(script, keys=["mykey"]) == "Hello" ``` ---------------------------------------- TITLE: Demonstrating Redis SMOVE with Upstash (TypeScript) DESCRIPTION: This example shows how to use the Redis SMOVE command via the Upstash Redis client in TypeScript. It first adds members to a source set using SADD and then moves a specific member from the source set to a destination set using SMOVE. The response indicates success (1), and the comments show the state of the sets after the operation. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/smove.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.sadd("original", "a", "b", "c"); const moved = await redis.smove("original", "destination", "a"); // moved: 1 // original: ["b", "c"] // destination: ["a"] ``` ---------------------------------------- TITLE: Simple ZINTER Redis Python DESCRIPTION: Demonstrates a basic ZINTER operation in Python using the `redis` client. It shows adding elements to two sorted sets and then finding their intersection, verifying the expected result containing only the common member 'c'. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zinter.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zinter(["key1", "key2"]) assert result == ["c"] ``` ---------------------------------------- TITLE: Check Notification Configuration with cURL DESCRIPTION: Retrieves the current value of the `notify-keyspace-events` configuration option using the Upstash REST API via cURL to check which notifications are active. Requires `UPSTASH_REDIS_REST_TOKEN` and `UPSTASH_REDIS_REST_URL` environment variables. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/keyspacenotifications.mdx#_snippet_5 LANGUAGE: bash CODE: ``` curl -X POST \ -d '["CONFIG", "GET", "notify-keyspace-events"]' \ -H "Authorization: Bearer $UPSTASH_REDIS_REST_TOKEN" \ $UPSTASH_REDIS_REST_URL ``` ---------------------------------------- TITLE: Retrieving Hash Values with Upstash Redis (TypeScript) DESCRIPTION: This snippet demonstrates fetching all values from a Redis hash using the @upstash/redis library in TypeScript. It first populates a hash with two fields using `hset` and then calls `hvals` to retrieve all the values from that hash, printing the resulting array. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hvals.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.hset("key", { field1: "Hello", field2: "World" }) const values = await redis.hvals("key") console.log(values) // ["Hello", "World"] ``` ---------------------------------------- TITLE: Set Multiple JSON Values - Upstash Redis Python DESCRIPTION: This snippet demonstrates how to use the `json.mset` method provided by the Upstash Redis Python client. It allows setting multiple JSON values at different paths across potentially multiple keys using a single command by providing a list of (key, path, value) tuples. Prerequisites include an initialized Redis client instance (`redis`). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/mset.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.json.mset([(key, "$.path", value), (key2, "$.path2", value2)]) ``` ---------------------------------------- TITLE: Setting up Sidekiq Dependencies in Ruby DESCRIPTION: These bash commands use Bundler to initialize a Gemfile for a Ruby project and add the Sidekiq gem as a dependency. This is a prerequisite step before writing any Sidekiq code. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/sidekiq.mdx#_snippet_0 LANGUAGE: bash CODE: ``` bundle init bundle add sidekiq ``` ---------------------------------------- TITLE: Adding Start Script - JSON DESCRIPTION: This JSON snippet adds a 'start' script to the package.json file, defining the command to run the Node.js application (index.js) when the project starts. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/cloud_run_sessions.mdx#_snippet_4 LANGUAGE: json CODE: ``` "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index" } ``` ---------------------------------------- TITLE: Executing ZDIFFSTORE Redis Command (TypeScript) DESCRIPTION: This snippet demonstrates how to use a Redis client library in TypeScript to execute the `ZDIFFSTORE` command. It calculates the difference between sorted sets named "key1" and "key2" and stores the resulting set in "destination". It expects a connected Redis client instance (`redis`) and returns a promise that resolves to the number of elements in the destination set. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zdiffstore.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` const values = await redis.zdiffstore("destination", 2, "key1", "key2"); ``` ---------------------------------------- TITLE: Incrementing Member Score in Sorted Set (TypeScript) DESCRIPTION: Shows how to use the ZADD command with the `incr` option (which makes it behave like ZINCRBY) to increment the score of a single existing member. Note: The code uses 'cincrh' which appears to be a typo for 'incr'. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zadd.mdx#_snippet_4 LANGUAGE: ts CODE: ``` await redis.zadd( "key", { cincrh: true }, { score: 2, member: "member" }, ) ``` ---------------------------------------- TITLE: Calling JSON.OBJKEYS with Python DESCRIPTION: This snippet demonstrates how to call the JSON.OBJKEYS command using a Python Redis client library. It shows how to specify the key holding the JSON document and the path to the target object. The function returns a list of keys found at the specified path. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/objkeys.mdx#_snippet_0 LANGUAGE: python CODE: ``` keys = redis.json.objkeys("key", "$.path") ``` ---------------------------------------- TITLE: Getting Set Difference with SDIFF using Python DESCRIPTION: This snippet demonstrates how to use the SDIFF command in Python. It first adds elements to two sets ('set1' and 'set2') using 'sadd', then calls 'sdiff' with the set keys, and finally asserts that the result is the expected difference set. It requires a Redis connection object (redis). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/sdiff.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); assert redis.sdiff("set1", "set2") == {"a", "b"} ``` ---------------------------------------- TITLE: Using HKEYS with Python Redis Client DESCRIPTION: This Python snippet demonstrates retrieving all field names from a Redis hash using `hkeys` after first populating the hash using `hset`. It uses a Python Redis client library and asserts the expected list of field names. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hkeys.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hkeys("myhash") == ["field1", "field2"] ``` ---------------------------------------- TITLE: Scanning Redis Hash with Match Option - TypeScript DESCRIPTION: Illustrates how to use the `hscan` command with the `match` option to filter returned fields based on a glob-style pattern. This example filters for fields starting with 'user*' and logs the resulting cursor and the filtered fields/values. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hscan.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const [newCursor, fields] = await redis.hscan("key", 0, { match: "user*" }); console.log(newCursor); // likely `0` since this is a very small hash console.log(fields); // ["username", "chronark"] ``` ---------------------------------------- TITLE: Storing Redis Sorted Set Intersection (Simple) - TypeScript DESCRIPTION: This snippet demonstrates the basic usage of the zinterstore command using the @upstash/redis client. It populates two sorted sets ('key1', 'key2') with members and scores, then calculates their intersection and stores the result in a new key ('destination'). The command requires the destination key, the count of input keys, and an array of input key names. The example logs the number of elements in the resulting sorted set. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zinterstore.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zinterstore("destination", 2, ["key1", "key2"]); console.log(res) // 1 ``` ---------------------------------------- TITLE: Setting and Verifying Hash Field Expiry in Python DESCRIPTION: This Python snippet demonstrates how to first set a specific field within a Redis hash using the `redis.hset` command, and subsequently apply a 1-second expiry to that field using `redis.hexpire`. The `assert` statement verifies that the `hexpire` call successfully returns `[1]`, indicating the expiry was set. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hexpire.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.hset(hash_name, field, value) assert redis.hexpire(hash_name, field, 1) == [1] ``` ---------------------------------------- TITLE: Retrieving ZRANGE by Score (TypeScript) DESCRIPTION: This snippet illustrates using the byScore option for ZRANGE. After adding three members, it calls zrange with byScore: true, specifying a score range of 1 to 2. The command returns members whose scores fall within this range, resulting in ["m1", "m2"]. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zrange.mdx#_snippet_2 LANGUAGE: typescript CODE: ``` await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, { score: 3, member: "m3" }, ) const res = await redis.zrange("key", 1, 2, { byScore: true }) console.log(res) // ["m1", "m2"] ``` ---------------------------------------- TITLE: Execute ZREMRANGEBYSCORE command in TypeScript DESCRIPTION: This snippet shows how to call the ZREMRANGEBYSCORE command using a Redis client library in TypeScript. It targets a sorted set identified by "key" and removes all members whose scores are between 2 (inclusive) and 5 (inclusive). The operation returns a promise that resolves to the count of elements removed. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zremrangebyscore.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.zremrangebyscore("key", 2, 5) ``` ---------------------------------------- TITLE: Retrieving Multiple Hash Fields with Redis HMGET (TypeScript) DESCRIPTION: This snippet demonstrates how to use the Redis HMGET command to retrieve specific fields from a hash key after setting it with HSET. It shows the necessary parameters (key and field names) and logs the resulting object containing the requested fields and their values. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hmget.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.hset("key", { id: 1, username: "chronark", name: "andreas" }); const fields = await redis.hmget("key", "username", "name"); console.log(fields); // { username: "chronark", name: "andreas" } ``` ---------------------------------------- TITLE: Popping Single Element with LPOP (TypeScript) DESCRIPTION: Demonstrates using the `lpop` command without a count to remove and return a single element from the beginning of a Redis list. The example first adds elements using `rpush`. The command returns the popped element or `null` if the list is empty. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/lpop.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.rpush("key", "a", "b", "c"); const element = await redis.lpop("key"); console.log(element); // "a" ``` ---------------------------------------- TITLE: Performing Set Union with SUNIONSTORE Python DESCRIPTION: This Python snippet demonstrates how to populate two Redis sets ('set1', 'set2') using the 'sadd' command and then use 'sunionstore' to compute their union, storing the result in a new set named 'destination'. It requires a connected Redis client instance and the redis-py library. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/sunionstore.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); redis.sunionstore("destination", "set1", "set2") ``` ---------------------------------------- TITLE: Performing SINTER on Redis Sets - Python DESCRIPTION: This code snippet demonstrates how to use a Redis client library in Python to add elements to two sets ('set1' and 'set2') and then perform the SINTER operation to find and assert their intersection. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/sinter.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); assert redis.sinter("set1", "set2") == {"c"} ``` ---------------------------------------- TITLE: Append String using JSON.STRAPPEND in Python DESCRIPTION: This snippet demonstrates how to call the Redis JSON.STRAPPEND command using a Python client library. It appends the specified 'value' string to the JSON string element found at the given 'path' within the JSON document stored under the 'key'. The command returns a list containing the length of the string after the append operation. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/strappend.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.json.strappend("key", "$.path.to.str", "abc") ``` ---------------------------------------- TITLE: Configure Redis URL Environment Variable DESCRIPTION: Shows the content of a `.env` file used to store the connection URL for the Upstash Redis database. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/auto_complete_with_serverless_redis.mdx#_snippet_5 LANGUAGE: text CODE: ``` REDIS_URL=YOUR_REDIS_URL ``` ---------------------------------------- TITLE: Initializing Express App with Redis Session Store - JavaScript DESCRIPTION: This JavaScript code sets up an Express application with session management backed by a Redis store using `connect-redis`. It requires dependencies like express, redis, connect-redis, express-session, and parseurl. The code initializes a Redis client, configures the session middleware to use the Redis store, and includes a simple middleware to track page views per session. Note that the Redis client connection details (`redis.createClient`) need to be replaced with actual connection information. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/express_session.mdx#_snippet_0 LANGUAGE: javascript CODE: ``` var express = require("express"); var parseurl = require("parseurl"); var session = require("express-session"); const redis = require("redis"); var RedisStore = require("connect-redis")(session); var client = redis.createClient({ // REPLACE HERE }); var app = express(); app.use( session({ store: new RedisStore({ client: client }), secret: "forest squirrel", resave: false, saveUninitialized: true, }) ); app.use(function (req, res, next) { if (!req.session.views) { req.session.views = {}; } // get the url pathname var pathname = parseurl(req).pathname; // count the views req.session.views[pathname] = (req.session.views[pathname] || 0) + 1; next(); }); app.get("/foo", function (req, res, next) { res.send("you viewed this page " + req.session.views["/foo"] + " times"); }); app.get("/bar", function (req, res, next) { res.send("you viewed this page " + req.session.views["/bar"] + " times"); }); app.listen(3000, function () { console.log("Example app listening on port 3000!"); }); ``` ---------------------------------------- TITLE: Incrementing JSON Number in Redis Python DESCRIPTION: This Python snippet demonstrates how to use the `redis.json.numincrby` method to increment a numeric value located at a specific JSON path within a Redis key. It shows the command call with sample arguments and assigns the returned new value to a variable. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/numincrby.mdx#_snippet_0 LANGUAGE: python CODE: ``` newValue = redis.json.numincrby("key", "$.path.to.value", 2) ``` ---------------------------------------- TITLE: Configuring Upstash Redis Credentials - env DESCRIPTION: Defines environment variables required to connect to the Upstash Redis database. These variables, UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN, should be stored securely, typically in a `.env` file for local development, to provide the Redis client with connection details. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/vercel-functions-pages-router.mdx#_snippet_1 LANGUAGE: env CODE: ``` UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` ---------------------------------------- TITLE: Configure Upstash Redis Environment Variables DESCRIPTION: This snippet shows the content of the `.env` file required to configure the connection to the Upstash Redis database. It includes placeholders for your specific Redis REST URL and token, which must be replaced with the actual values obtained from the Upstash console. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/python_session.mdx#_snippet_1 LANGUAGE: bash CODE: ``` UPSTASH_REDIS_REST_URL=your_upstash_redis_url UPSTASH_REDIS_REST_TOKEN=your_upstash_redis_token ``` ---------------------------------------- TITLE: Performing Set Union and Storing with Upstash Redis (TypeScript) DESCRIPTION: This snippet demonstrates using the Upstash Redis client to add members to two sets ('set1', 'set2') using SADD and then calculate their union, storing the result in a third set ('destination') using SUNIONSTORE. It requires an initialized 'redis' client instance. The successful execution results in the 'destination' set containing the union of 'set1' and 'set2'. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/sunionstore.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); await redis.sunionstore("destination", "set1", "set2"); ``` ---------------------------------------- TITLE: Multiplying JSON Number in Python DESCRIPTION: Demonstrates how to invoke the `JSON.NUMMULTBY` command using the Python Redis client. It shows multiplying a number at `$.path.to.value` within the key `key` by 2. Requires a configured Redis client instance with JSON support. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/nummultby.mdx#_snippet_0 LANGUAGE: python CODE: ``` newValue = redis.json.nummultby("key", "$.path.to.value", 2) ``` ---------------------------------------- TITLE: Popping Multiple Elements with RPOP (TypeScript) DESCRIPTION: Shows how to use `redis.rpop` with the `count` argument to remove and return multiple elements from the end of a list. It first pushes elements using `rpush` and then pops the specified number, logging the result. Expects an array of string values as output. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/rpop.mdx#_snippet_1 LANGUAGE: typescript CODE: ``` await redis.rpush("key", "a", "b", "c"); const element = await redis.rpop("key", 2); console.log(element); // ["c", "b"] ``` ---------------------------------------- TITLE: Aggregating ZUNIONSTORE Scores in Python DESCRIPTION: This snippet illustrates using the zunionstore command with score aggregation in Python. It performs a union of two sorted sets (key1 and key2) with common members. The withscores=True option includes scores, and aggregate="SUM" adds scores of identical members from different sets. The result is a list of tuples (member, aggregated_score). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zunionstore.mdx#_snippet_1 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zunionstore(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ``` ---------------------------------------- TITLE: Storing Set Difference using ZDIFFSTORE (Python) DESCRIPTION: This snippet demonstrates how to use the ZDIFFSTORE command in Python. It populates two sorted sets using ZADD, calculates the difference between the first set (key1) and the second set (key2), stores the result in the 'dest' key, and asserts that the resulting set contains 2 elements. It requires a connected Python Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zdiffstore.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) # a and b assert redis.zdiffstore("dest", ["key1", "key2"]) == 2 ``` ---------------------------------------- TITLE: Performing Redis PING Command (Python) DESCRIPTION: This snippet demonstrates how to send a PING command to a Redis server using a Python client. It calls the `ping()` method on an initialized `redis` client instance and asserts that the response is 'PONG', confirming the server is alive and responsive. Requires an established connection via a Redis client library. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/auth/ping.mdx#_snippet_0 LANGUAGE: python CODE: ``` assert redis.ping() == "PONG" ``` ---------------------------------------- TITLE: Applying Custom Rate Consumption in Fixed Window Ratelimit Python DESCRIPTION: This snippet shows how to use the `rate` parameter when calling the `limit` method of an Upstash rate limiter, allowing a single request to consume more than one "token" from the allowed limit. This is particularly useful for scenarios where different requests have different costs or weights, such as processing batches or limiting based on token counts. It initializes a FixedWindow limiter and applies a custom rate of 5. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-py/features.mdx#_snippet_2 LANGUAGE: python CODE: ``` from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), ) # pass rate as 5 to subtract 5 from the number of # allowed requests in the window: identifier = "api" response = ratelimit.limit(identifier, rate=5) ``` ---------------------------------------- TITLE: Setting multiple keys using mset in Python DESCRIPTION: This snippet demonstrates how to use the `mset` method of a Redis client object to set multiple key-value pairs atomically. It takes a dictionary where keys are Redis keys and values are the corresponding values to set. The command returns a boolean indicating success. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/mset.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.mset({ "key1": "value1", "key2": "value2" }) ``` ---------------------------------------- TITLE: Checking field existence after setting in Redis using Python DESCRIPTION: This snippet demonstrates how to use the HEXISTS command in Python after setting a value with HSET. It requires a Redis client library (like redis-py). It first sets a field 'field' with value 'value' in hash 'key', then asserts that HEXISTS correctly returns True for that field. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hexists.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.hset("key", "field", "value") assert redis.hexists("key", "field") == True ``` ---------------------------------------- TITLE: Renaming Key with Upstash Redis Client in TypeScript DESCRIPTION: Demonstrates how to rename a key using the `rename` method of the Upstash Redis client in TypeScript. It takes the original key name (source) and the new key name (destination) as arguments and returns a promise that resolves to 'OK' upon success. This operation requires an initialized Upstash Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/rename.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.rename("old", "new"); ``` ---------------------------------------- TITLE: Forgetting Cache Key in Laravel PHP DESCRIPTION: Demonstrates how to remove a specific key from the Laravel cache using the `Cache::forget` method. This is typically used for cache invalidation after data modification. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/laravel_caching.mdx#_snippet_15 LANGUAGE: php CODE: ``` Cache::forget('todos'); ``` ---------------------------------------- TITLE: Calling ZPOPMAX with Redis Client (TypeScript) DESCRIPTION: Demonstrates how to call the Redis ZPOPMAX command using a TypeScript Redis client library. It removes and returns up to 4 members with the highest scores from the sorted set identified by 'key'. The result is awaited as the operation is asynchronous. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zpopmax.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const popped = await redis.zpopmax("key", 4); ``` ---------------------------------------- TITLE: Deleting Redis Hash Fields - Python DESCRIPTION: This Python snippet demonstrates the usage of the Redis HDEL command. It first sets two fields ('field1' and 'field2') in a hash named 'myhash' using `hset`, and then uses `hdel` to remove both fields. The assertion verifies that `hdel` returns 2, indicating that two fields were successfully deleted. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hdel.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.hset("myhash", "field1", "Hello") redis.hset("myhash", "field2", "World") assert redis.hdel("myhash", "field1", "field2") == 2 ``` ---------------------------------------- TITLE: Appending Entry with Trimming (Python) DESCRIPTION: This snippet shows how to append an entry to a Redis stream while applying trimming rules using the `xadd` command in Python. It specifies the `MAXLEN` trim type with a threshold and comparison operator to manage stream size. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/stream/xadd.mdx#_snippet_1 LANGUAGE: py CODE: ``` redis.xadd(key, "*", { "name": "John Doe", "age": 30 }, { "trim": { "type": "MAXLEN", "threshold": 1000, "comparison": "=" } }) ``` ---------------------------------------- TITLE: Getting Sorted Set Cardinality with Python DESCRIPTION: This snippet demonstrates how to use the ZCARD command in Python. It first adds multiple elements to a sorted set named 'myset' using `redis.zadd` and then retrieves the total number of elements in that set using `redis.zcard`, asserting that the count is correct. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zcard.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) assert redis.zcard("myset") == 3 ``` ---------------------------------------- TITLE: Configure Upstash MCP Stdio Server for Copilot (JSON) DESCRIPTION: This JSON snippet configures the Upstash MCP server for the Copilot client using the `stdio` transport mode within the `.vscode/mcp.json` file. It defines a server named 'upstash' with type 'stdio' that runs locally via `npx`, executing the `@upstash/mcp-server run` command. It requires the user's Upstash email and API key placeholders to be replaced for authentication. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/mcp.mdx#_snippet_1 LANGUAGE: json CODE: ``` { "servers": { "upstash": { "type": "stdio", "command": "npx", "args": [ "-y", "@upstash/mcp-server", "run", "", "" ] } } } ``` ---------------------------------------- TITLE: Using RPUSHX with Redis in Python DESCRIPTION: This Python example demonstrates the `RPUSHX` command using a Redis client. It shows pushing elements to an existing list and verifying the result, then attempts to push to a non-existent key, asserting that the operation returns 0 as expected. It requires a Redis client instance (`redis`) and potentially access to `lrange` for verification. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/rpushx.mdx#_snippet_0 LANGUAGE: python CODE: ``` assert redis.rpushx("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["one", "two", "three"] # Non existing key assert redis.rpushx("non-existent-list", "one") == 0 ``` ---------------------------------------- TITLE: Initializing Upstash Redis Client in Cloudflare Workers (TypeScript) DESCRIPTION: Illustrates how to initialize the Upstash Redis client for Cloudflare Workers. It shows explicit initialization with URL and token (set via `wrangler secret put` or dashboard) and using `fromEnv()`, which loads credentials from global environment (service workers) or the env object (module workers). Requires the `@upstash/redis/cloudflare` package. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/deployment.mdx#_snippet_2 LANGUAGE: TypeScript CODE: ``` import { Redis } from "@upstash/redis/cloudflare" const redis = new Redis({ url: , token: , }) // or load directly from global env // service worker const redis = Redis.fromEnv() // module worker export default { async fetch(request: Request, env: Bindings) { const redis = Redis.fromEnv(env) // ... } } ``` ---------------------------------------- TITLE: Popping Single Element with LPOP (Python) DESCRIPTION: This snippet demonstrates how to use the `LPOP` command in Python to remove and return the first element from a Redis list. It first populates the list using `RPUSH` and then calls `LPOP` on the list key, asserting that the returned value is the first element pushed. This usage pops only one element by default. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/lpop.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.rpush("mylist", "one", "two", "three") assert redis.lpop("mylist") == "one" ``` ---------------------------------------- TITLE: SET Command with Old Value Retrieval (get) in Python DESCRIPTION: Demonstrates using the `get=True` option with the Redis SET command in Python, which causes the command to return the old value of the key before it was set to the new value. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/set.mdx#_snippet_3 LANGUAGE: python CODE: ``` # Get the old value stored at the key. assert redis.set("key", "new-value", get=True) == "old-value" ``` ---------------------------------------- TITLE: Scanning Redis Hash (Basic) with HSCAN - TypeScript DESCRIPTION: Demonstrates the basic usage of the `hscan` command to iterate through fields and values in a Redis hash after populating it with `hset`. It shows how to initialize the scan with cursor `0` and logs the returned new cursor and the array of fields and values. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hscan.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.hset("key", { id: 1, username: "chronark", name: "andreas" }); const [newCursor, fields] = await redis.hscan("key", 0); console.log(newCursor); // likely `0` since this is a very small hash console.log(fields); // ["id", 1, "username", "chronark", "name", "andreas"] ``` ---------------------------------------- TITLE: Fetching List Element with LINDEX in TypeScript DESCRIPTION: This example demonstrates how to use the `lindex` command in TypeScript after adding elements to a list using `rpush`. It adds 'a', 'b', and 'c' to a list named 'key' and then retrieves and logs the element at index 0. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/lindex.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.rpush("key", "a", "b", "c"); const element = await redis.lindex("key", 0); console.log(element); // "a" ``` ---------------------------------------- TITLE: Appending Value with Redis Client in Python DESCRIPTION: This Python example illustrates the usage of the Redis APPEND command. It shows how to initialize a string key with an initial value, append additional content to it, and then assert both the return value of APPEND (the new length of the string) and the final state of the key's value using the GET command. It assumes a Redis client instance named `redis` is already initialized. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/string/append.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.set("key", "Hello") assert redis.append("key", " World") == 11 assert redis.get("key") == "Hello World" ``` ---------------------------------------- TITLE: Exporting Data with upstash-redis-dump (Bash) DESCRIPTION: This command uses the `upstash-redis-dump` tool to export data from a source regional Upstash Redis database. It requires providing the database host, port, and password, and specifies database 0. The output is redirected to a file named `redis.dump`. SOURCE: https://github.com/upstash/docs/blob/main/redis/howto/migratefromregionaltoglobal.mdx#_snippet_1 LANGUAGE: bash CODE: ``` upstash-redis-dump -db 0 -host YOUR_REGIONAL_HOST -port YOUR_DATABASE_PORT -pass YOUR_PASSWORD -tls > redis.dump ``` ---------------------------------------- TITLE: Using RENAMENX with Redis in Python DESCRIPTION: Demonstrates how to use the `renamenx` method of a Redis client in Python. It shows scenarios where the rename fails (destination key already exists) and succeeds (destination key does not exist), verifying the state of the keys after the operations. Requires a connected Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/renamenx.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.set("key1", "Hello") redis.set("key2", "World") # Rename failed because "key2" already exists. assert redis.renamenx("key1", "key2") == False assert redis.renamenx("key1", "key3") == True assert redis.get("key1") is None assert redis.get("key2") == "World" assert redis.get("key3") == "Hello" ``` ---------------------------------------- TITLE: Checking TTL for Redis Keys (Python) DESCRIPTION: This Python snippet demonstrates how to use a Redis client's 'ttl' command. It shows the expected return values (-1, positive, -2) for keys with no expiration, a set expiration, and non-existent keys, respectively. It requires a connected Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/generic/ttl.mdx#_snippet_0 LANGUAGE: py CODE: ``` # Get the TTL of a key redis.set("my-key", "value") assert redis.ttl("my-key") == -1 redis.expire("my-key", 10) assert redis.ttl("my-key") > 0 # Non existent key assert redis.ttl("non-existent-key") == -2 ``` ---------------------------------------- TITLE: Calculating and Logging Redis Set Difference - TypeScript DESCRIPTION: This snippet demonstrates adding members to two Redis sets (`set1` and `set2`) using `redis.sadd`. It then calculates the difference between `set1` and `set2` using `redis.sdiff` (likely a client library method) and logs the result, which shows the members present in the first set but not the subsequent ones. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/sdiffstore.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); await redis.sdiff("dest", "set1", "set2"); console.log(diff); // ["a", "b"] ``` ---------------------------------------- TITLE: Calculating ZDIFF Simply (Python) DESCRIPTION: Demonstrates how to use the `redis.zdiff` command to find the difference between two sorted sets without including scores. It shows adding data to two sets and then calling `zdiff` with a list of keys and asserting the expected difference. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zdiff.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zdiff(["key1", "key2"]) assert result == ["a", "b"] ``` ---------------------------------------- TITLE: Trimming a Redis List Python DESCRIPTION: This snippet demonstrates how to use the `LTRIM` command in a Python Redis client. It first pushes elements onto a list, then calls `ltrim` to keep only elements from index 0 to 1 (inclusive), and finally uses `lrange` to assert that the list now contains only the expected elements. Requires a Redis client instance named `redis`. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/ltrim.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.rpush("mylist", "one", "two", "three") assert redis.ltrim("mylist", 0, 1) == True assert redis.lrange("mylist", 0, -1) == ["one", "two"] ``` ---------------------------------------- TITLE: Setting JSON Value If Exists (XX) - Python DESCRIPTION: Illustrates using the json.set command with the xx=true option in Python. This sets the value at the specified path only if the path currently exists within the JSON document. Requires key, path, and value to be defined. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/set.mdx#_snippet_2 LANGUAGE: python CODE: ``` value = ... redis.json.set(key, "$.path", value, xx=true) ``` ---------------------------------------- TITLE: Getting Multiple Random Fields from Hash in TypeScript DESCRIPTION: Shows how to use HRANDFIELD with a count argument to retrieve a specified number of random field names from a hash, illustrating the output as an array. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hrandfield.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const randomFields = await redis.hrandfield("key", 2); console.log(randomFields); // ["id", "username"] or any other combination ``` ---------------------------------------- TITLE: Configure Upstash MCP Stdio Server for Claude/Cursor (JSON) DESCRIPTION: This JSON snippet configures the Upstash MCP server for Claude or Cursor clients using the `stdio` transport mode within the client's configuration file (e.g., `mcp.json`). It defines an MCP server named 'upstash' that runs locally via `npx`, executing the `@upstash/mcp-server run` command and requiring the user's Upstash email and API key as command-line arguments. This configuration is typically used for local development. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/mcp.mdx#_snippet_0 LANGUAGE: json CODE: ``` { "mcpServers": { "upstash": { "command": "npx", "args": [ "-y", "@upstash/mcp-server", "run", "", "" ] } } } ``` ---------------------------------------- TITLE: Define RatelimitResponse Type - TypeScript DESCRIPTION: Defines the `RatelimitResponse` type returned by `limit` and `blockUntilReady`. It includes properties like `success`, `limit`, `remaining`, `reset`, a `pending` promise for asynchronous operations, and optional `reason` and `deniedValue` fields. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/methods.mdx#_snippet_1 LANGUAGE: TypeScript CODE: ``` export type RatelimitResponse = { /** * Whether the request may pass(true) or exceeded the limit(false) */ success: boolean; /** * Maximum number of requests allowed within a window. */ limit: number; /** * How many requests the user has left within the current window. */ remaining: number; /** * Unix timestamp in milliseconds when the limits are reset. */ reset: number; /** * For the MultiRegion setup we do some synchronizing in the background, after returning the current limit. * Or when analytics is enabled, we send the analytics asynchronously after returning the limit. * In most case you can simply ignore this. * * On Vercel Edge or Cloudflare workers, you need to explicitly handle the pending Promise like this: * * ```ts * const { pending } = await ratelimit.limit("id") * context.waitUntil(pending) * ``` * * See `waitUntil` documentation in * [Cloudflare](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/#contextwaituntil) * and [Vercel](https://vercel.com/docs/functions/edge-middleware/middleware-api#waituntil) * for more details. * ``` */ pending: Promise; /** * Reason behind the result in `success` field. * - Is set to "timeout" when request times out * - Is set to "cacheBlock" when an identifier is blocked through cache without calling redis because it was * rate limited previously. * - Is set to "denyList" when identifier or one of ip/user-agent/country parameters is in deny list. To enable * deny list, see `enableProtection` parameter. To edit the deny list, see the Upstash Ratelimit Dashboard * at https://console.upstash.com/ratelimit. * - Is set to undefined if rate limit check had to use Redis. This happens in cases when `success` field in * the response is true. It can also happen the first time sucecss is false. */ reason?: RatelimitResponseType; /** * The value which was in the deny list if reason: "denyList" */ deniedValue?: string; }; ``` ---------------------------------------- TITLE: Adding Members and Counting with Redis (Python) DESCRIPTION: This snippet demonstrates how to add multiple members with their scores to a Redis sorted set using the `zadd` command. It then shows how to count all elements in the sorted set using the `zlexcount` command with the full range ('-' to '+') and asserts the expected count. This requires a connected Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zmscore.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zlexcount("myset", "-", "+") == 3 ``` ---------------------------------------- TITLE: Executing Basic EVAL_RO Script in Python DESCRIPTION: This snippet demonstrates how to execute a simple read-only Lua script using the EVAL_RO command in Python. It shows defining the script, setting a key, calling eval_ro with the script and the key, and asserting the result. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/scripts/eval_ro.mdx#_snippet_0 LANGUAGE: python CODE: ``` script = """ local value = redis.call("GET", KEYS[1]) return value """ redis.set("mykey", "Hello") assert redis.eval_ro(script, keys=["mykey"]) == "Hello" ``` ---------------------------------------- TITLE: Getting Rank with ZRANK in Python DESCRIPTION: This snippet demonstrates how to use the ZRANK command with a Redis client in Python. It first adds members with scores to a sorted set named 'myset' using ZADD, then uses ZRANK to find the 0-based rank of existing members ('a', 'b', 'c') and asserts the expected integer output. It also shows querying a non-existing member ('d') and asserts that the result is None. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zrank.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zrank("myset", "a") == 0 assert redis.zrank("myset", "d") == None assert redis.zrank("myset", "b") == 1 assert redis.zrank("myset", "c") == 2 ``` ---------------------------------------- TITLE: Initializing Redis Client with Deserialization Disabled (TypeScript) DESCRIPTION: Configures the Upstash Redis client to disable the default automatic JSON deserialization of data fetched from Redis. This gives manual control over data interpretation. Requires `@upstash/redis`. The constructor takes an options object, including `automaticDeserialization`. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/advanced.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` const redis = new Redis({ // ... automaticDeserialization: false, }); ``` ---------------------------------------- TITLE: Finding First Element Index with LPOS Python DESCRIPTION: Demonstrates the basic usage of the LPOS command to find the index of the first matching element in a list. It first pushes elements 'a', 'b', 'c' to a list named 'key', then asserts that the index of 'b' is 1. Requires a Redis client library. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/lpos.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.rpush("key", "a", "b", "c"); assert redis.lpos("key", "b") == 1 ``` ---------------------------------------- TITLE: Executing JSON.FORGET Redis command - TypeScript DESCRIPTION: Demonstrates using a TypeScript Redis client to execute the `JSON.FORGET` command. This command is used to remove an element or members from a JSON document stored under a specific key at a given JSON path. It requires a Redis client instance and takes the key and path as arguments. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/forget.mdx#_snippet_0 LANGUAGE: TypeScript CODE: ``` await redis.json.forget("key", "$.path.to.value"); ``` ---------------------------------------- TITLE: Retrieving Multiple Random Members from Redis Set (TypeScript) DESCRIPTION: This snippet shows how to add members to a Redis set and then retrieve multiple random members using the `srandmember` command with the count parameter. It requires a Redis client library. The command takes the set key and the desired count as input and returns an array of member strings. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/set/srandmember.mdx#_snippet_1 LANGUAGE: ts CODE: ``` await redis.sadd("set", "a", "b", "c"); const members = await redis.srandmember("set", 2); console.log(members); // ["a", "b"] ``` ---------------------------------------- TITLE: Demonstrating HSETNX Command Usage in Python DESCRIPTION: This snippet demonstrates how to use the `hsetnx` command with a Redis client in Python. It shows setting a field ("field1") in a hash ("myhash") with a value ("Hello"), which succeeds because the field doesn't exist. It then attempts to set the same field with a different value ("World"), which fails because the field already exists, returning `False`. This requires a connected Redis client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hsetnx.mdx#_snippet_0 LANGUAGE: Python CODE: ``` assert redis.hsetnx("myhash", "field1", "Hello") == True assert redis.hsetnx("myhash", "field1", "World") == False ``` ---------------------------------------- TITLE: Setting Hash Field Expiry with HPEXPIREAT in Python DESCRIPTION: This snippet demonstrates setting a field in a hash and then applying an expiration time in milliseconds using the `hpexpireat` command in Python. It first sets a field with `redis.hset` and then asserts that `redis.hpexpireat` successfully sets the expiration for that field to 1 second in the future (current time + 1000ms), expecting a return value of `[1]` for success. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/hash/hpexpireat.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.hset(hash_name, field, value) assert redis.hpexpireat(hash_name, field, int(time.time() * 1000) + 1000) == [1] ``` ---------------------------------------- TITLE: Executing custom Redis commands in Python DESCRIPTION: Shows how to execute any arbitrary Redis command using the `execute` method of the client instance by providing the command and its arguments as a list. This is useful for commands not explicitly implemented in the client library. Requires an initialized `redis` client instance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/features.mdx#_snippet_1 LANGUAGE: python CODE: ``` redis.execute(["XLEN", "test_stream"]) ``` ---------------------------------------- TITLE: Initializing Ratelimit Client with Auto IP Protection (TS) DESCRIPTION: This TypeScript snippet shows how to initialize the Upstash Ratelimit client to enable the Auto IP Deny List feature by setting `enableProtection` to `true`. It requires a Redis connection and a defined rate limiting strategy. Enabling protection allows the client to automatically block malicious IP addresses based on integrated deny lists. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/traffic-protection.mdx#_snippet_2 LANGUAGE: ts CODE: ``` const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), enableProtection: true, }); ``` ---------------------------------------- TITLE: Creating Bull Queue Producer Function in JavaScript DESCRIPTION: This JavaScript code defines an AWS Lambda function ('hello') that acts as the producer. It initializes a Bull queue instance configured with specific connection details and settings for Upstash Redis to manage queue behavior and resource usage. It then adds the incoming event payload as a job to the queue. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/job_processing.mdx#_snippet_2 LANGUAGE: JavaScript CODE: ``` var Queue = require("bull"); var settings = { stalledInterval: 300000, // How often check for stalled jobs (use 0 for never checking). guardInterval: 5000, // Poll interval for delayed jobs and added jobs. drainDelay: 300, // A timeout for when the queue is in drained state (empty waiting for jobs). }; module.exports.hello = async (event) => { var taskQueue = new Queue( "employee registration", { redis: { port: 32016, host: "us1-upward-ant-32016.upstash.io", password: "ake4ff120d6b4216df220736be7eab087", tls: {}, }, }, settings ); await taskQueue.add({ event: event }); // TODO save the employee record to a database return { message: "New employee event enqueued! 34", event }; }; ``` ---------------------------------------- TITLE: Demonstrating Redis ZRANDMEMBER in Python DESCRIPTION: This snippet demonstrates how to first add members to a Redis sorted set using `zadd` and then retrieve random members using the `zrandmember` command. It shows fetching a single random member and multiple random members. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zrandmember.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) # "one" redis.zrandmember("myset") # ["one", "three"] redis.zrandmember("myset", 2) ``` ---------------------------------------- TITLE: Adding Redix Client to Supervision Tree (Elixir) DESCRIPTION: Adds the Redix client worker specification to the `children` list within the application's supervision tree defined in `application.ex`. It configures the Redix client with the extracted host, port, password, and specifies IPv6 socket options (`:inet6`) for Fly.io deployment. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/elixir.mdx#_snippet_3 LANGUAGE: Elixir CODE: ``` children = [ # ... { Redix, name: :redix, host: host, port: port, password: password, socket_opts: [:inet6] } ] ``` ---------------------------------------- TITLE: Append String to JSON Path in Redis (TypeScript) DESCRIPTION: This code snippet demonstrates how to use a TypeScript Redis client library to execute the `JSON.STRAPPEND` command. It appends a specified string value to the existing string value at a given JSON path within a document stored under a key in Redis. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/strappend.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.json.strappend("key", "$.path.to.str", "abc"); ``` ---------------------------------------- TITLE: Deleting JSON Path using Python DESCRIPTION: This code snippet demonstrates how to use a Python Redis client's JSON module to execute the `JSON.DEL` command. It targets a specific `key` and deletes the element(s) located at the provided `path` within the associated JSON document. This requires a Redis stack server supporting JSON and a Python client library like `redis-py` with JSON support. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/del.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.json.del("key", "$.path.to.value") ``` ---------------------------------------- TITLE: Inserting Values into JSON Array using Redis Client TypeScript DESCRIPTION: This snippet demonstrates calling the `json.arrinsert` method on a Redis client instance. It inserts values ("a", "b") into the JSON array located at the specified path (`$.path.to.array`) within the Redis key ("key"), starting at index 2. The method returns the new length of the modified array. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/arrinsert.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const length = await redis.json.arrinsert("key", "$.path.to.array", 2, "a", "b"); ``` ---------------------------------------- TITLE: Getting Keys by Pattern from Redis using TypeScript DESCRIPTION: This snippet demonstrates how to use the `redis.keys()` method from the Upstash Redis SDK to retrieve keys from Redis that match a specified glob-style pattern, specifically keys starting with 'prefix*'. Be aware that using the KEYS command with non-specific patterns on a large database can block operations. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/generic/keys.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const keys = await redis.keys("prefix*"); ``` ---------------------------------------- TITLE: Getting ZRANK with Upstash Redis Client (TypeScript) DESCRIPTION: This snippet demonstrates how to use a Redis client library (likely @upstash/redis) to get the rank of a member within a sorted set using the ZRANK command. It calls the asynchronous `rank` method on a `redis` client object, passing the key of the sorted set and the member name as arguments. The result is the integer rank of the member. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zrank.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const rank = await redis.rank("key", "member"); ``` ---------------------------------------- TITLE: Using Redis SPOP in Python (Single) DESCRIPTION: Demonstrates how to use the SPOP command in Python to remove and return a single random member from a Redis set. It first adds members to the set and then calls SPOP, asserting that the returned member is one of the originals. Requires a connected Redis client. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/spop.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.sadd("myset", "one", "two", "three") assert redis.spop("myset") in {"one", "two", "three"} ``` ---------------------------------------- TITLE: Passing Arguments to EVAL_RO Script in Python DESCRIPTION: This snippet illustrates how to pass arguments to a read-only Lua script executed via the EVAL_RO command in Python. It shows calling eval_ro with a script that returns an argument from ARGV and asserting the result. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/scripts/eval_ro.mdx#_snippet_1 LANGUAGE: python CODE: ``` assert redis.eval_ro("return ARGV[1]", args=["Hello"]) == "Hello" ``` ---------------------------------------- TITLE: Trimming a Redis List using LTRIM in TypeScript DESCRIPTION: This snippet demonstrates how to use the `lpush` command to add elements to a Redis list and the `ltrim` command to trim the list. It pushes elements 'a', 'b', 'c', 'd' and then trims the list to keep only elements from index 1 to 2, resulting in the list ['b', 'c']. This requires a Redis client instance, such as one provided by Upstash. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/list/ltrim.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.lpush("key", "a", "b", "c", "d"); await redis.ltrim("key", 1, 2); // the list is now ["b", "c"] ``` ---------------------------------------- TITLE: Calling JSON.STRLEN with Python DESCRIPTION: This example demonstrates how to use the `redis.json.strlen` method in Python to retrieve the length of a JSON string located at a specific path within a key. It requires a Redis client instance connected to an Upstash Redis database. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/strlen.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.json.strlen("key", "$.path.to.str") ``` ---------------------------------------- TITLE: Setting Hash Field and Expiration with HEXPIREAT in TypeScript DESCRIPTION: This snippet demonstrates how to first set a field and value within a Redis hash using `hset`, and then apply a field-specific expiration time using `hexpireat`. It sets the expiration to 10 seconds from the current time using a Unix timestamp. The output shows the result of the `hexpireat` command. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hexpireat.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.hset("my-key", "my-field", "my-value"); const expirationSet = await redis.hexpireat("my-key", "my-field", Math.floor(Date.now() / 1000) + 10); console.log(expirationSet); // [1] ``` ---------------------------------------- TITLE: Handling Large Numbers Returned as Strings (TypeScript) DESCRIPTION: Illustrates setting a large numeric value in Redis. It demonstrates that the `@upstash/redis` client returns such values as strings in JavaScript due to the language's inability to safely handle integers larger than `2^53 - 1`, preventing potential precision loss or incorrect parsing. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/troubleshooting.mdx#_snippet_4 LANGUAGE: typescript CODE: ``` await redis.set("key", "101600000000150081467"); const res = await redis("get"); // "101600000000150081467" ``` ---------------------------------------- TITLE: Using Custom Rate with limit Method (TypeScript) DESCRIPTION: Demonstrates how to pass the `rate` parameter to the `limit` method. This allows subtracting a custom value instead of the default 1, useful for rate limiting based on batch sizes or variable request costs. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/features.mdx#_snippet_4 LANGUAGE: TypeScript CODE: ``` const { success } = await ratelimit.limit("identifier", { rate: batchSize }); ``` ---------------------------------------- TITLE: Deploying SST App with Shell DESCRIPTION: Deploys the SST application, including the Next.js component and any other configured resources, to the specified cloud provider (AWS in this case) using the SST CLI. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/ion.mdx#_snippet_7 LANGUAGE: shell CODE: ``` sst deploy ``` ---------------------------------------- TITLE: Calculating ZDIFF with Scores (Python) DESCRIPTION: Demonstrates how to use the `redis.zdiff` command with the `withscores=True` argument to find the difference between two sorted sets and include the scores of the resulting elements from the first set. It shows adding data to two sets and then calling `zdiff` with the `withscores` flag and asserting the expected result with scores. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zdiff.mdx#_snippet_1 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"c": 3, "d": 4, "e": 5}) result = redis.zdiff(["key1", "key2"], withscores=True) assert result == [("a", 1), ("b", 2)] ``` ---------------------------------------- TITLE: Getting a Single Random Field from Hash in TypeScript DESCRIPTION: Demonstrates the basic usage of the HRANDFIELD command to retrieve a single random field name from a specified hash key after setting initial data using HSET. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/hash/hrandfield.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.hset("key", { id: 1, username: "chronark", name: "andreas" }); const randomField = await redis.hrandfield("key"); console.log(randomField); // one of "id", "username" or "name" ``` ---------------------------------------- TITLE: Popping Lowest Score Members from Sorted Set (Python) DESCRIPTION: This snippet demonstrates using a Python Redis client to interact with a sorted set. It first adds members 'a', 'b', and 'c' with scores 1, 2, and 3 respectively to a sorted set named "myset". Then, it calls `zpopmin` on "myset" to remove and return the member(s) with the lowest score(s), asserting that it correctly returns the member 'a' with score 1. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zpopmin.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zpopmin("myset") == [("a", 1)] ``` ---------------------------------------- TITLE: Calling JSON.FORGET - Redis/Upstash - Python DESCRIPTION: Demonstrates how to use a Python Redis client to call the JSON.FORGET command. This command deletes the element at the specified path within the JSON document stored at the given key. It requires a connected Redis client instance and returns the number of paths successfully deleted. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/forget.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.json.forget("key", "$.path.to.value") ``` ---------------------------------------- TITLE: Initializing Ratelimit Client with Deny Protection (TSX) DESCRIPTION: This snippet demonstrates initializing the Upstash Ratelimit client in TypeScript/TSX, enabling both deny list traffic protection and analytics by setting `enableProtection` and `analytics` to `true`. It configures the client with a Redis connection and a sliding window rate limiter. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ratelimit-ts/traffic-protection.mdx#_snippet_0 LANGUAGE: tsx CODE: ``` const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), enableProtection: true analytics: true, }); ``` ---------------------------------------- TITLE: Get ZSCORE with Upstash Redis TypeScript Client DESCRIPTION: This snippet demonstrates how to use the ZSCORE command with the Upstash Redis client in TypeScript. It first populates a sorted set named 'key' using ZADD with several members and their scores, and then retrieves the score for the member 'm2' using ZSCORE. The retrieved score is then logged to the console. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zscore.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, { score: 3, member: "m3" }, { score: 4, member: "m4" }, ) const score = await redis.zscore("key", "m2") console.log(score) // 2 ``` ---------------------------------------- TITLE: Manual Cache Invalidation by Table - TypeScript DESCRIPTION: Illustrates how to manually invalidate cached queries associated with a specific table name using the `$cache?.invalidate()` method. This is useful for scenarios where automatic invalidation might not be sufficient or desired. SOURCE: https://github.com/upstash/docs/blob/main/redis/integrations/drizzle.mdx#_snippet_7 LANGUAGE: typescript CODE: ``` // 👇 invalidate all queries that use the \`users\` table await db.$cache?.invalidate({ tables: ["usersTable"] }) ``` ---------------------------------------- TITLE: Append Values to JSON Array in Python DESCRIPTION: This snippet demonstrates using the `arrappend` method on the Upstash Redis JSON client in Python. It appends the value 'a' to the array located at the specified path '$.path.to.array' within the JSON document stored under the key 'key'. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/arrappend.mdx#_snippet_0 LANGUAGE: Python CODE: ``` redis.json.arrappend("key", "$.path.to.array", "a") ``` ---------------------------------------- TITLE: Deploying AWS CDK Stack (Shell) DESCRIPTION: Executes the necessary commands to synthesize the CDK application into CloudFormation templates (`cdk synth`), prepare the AWS environment (`cdk bootstrap`), and deploy the defined stack resources (`cdk deploy`) to your AWS account. SOURCE: https://github.com/upstash/docs/blob/main/redis/tutorials/api_with_cdk.mdx#_snippet_6 LANGUAGE: Shell CODE: ``` cdk synth cdk bootstrap cdk deploy ``` ---------------------------------------- TITLE: Popping First Element from JSON Array - TypeScript DESCRIPTION: Illustrates how to pop the first element (at index 0) from a JSON array located at a specified path within a Redis key using a TypeScript client method. It requires a Redis connection and a key containing a JSON array. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/arrpop.mdx#_snippet_1 LANGUAGE: ts CODE: ``` const firstElement = await redis.json.arrpop("key", "$.path.to.array", 0); ``` ---------------------------------------- TITLE: Executing GETRANGE Command using TypeScript DESCRIPTION: This snippet demonstrates how to call the Redis GETRANGE command using a TypeScript Redis client instance (likely from Upstash). It retrieves a substring of the value stored at the specified 'key' using inclusive start and end indices. The result is awaited and stored in the 'substring' variable. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/string/getrange.mdx#_snippet_0 LANGUAGE: ts CODE: ``` const substring = await redis.getrange("key", 2, 4); ``` ---------------------------------------- TITLE: Append to JSON Array with JSON.ARRAPPEND using TypeScript DESCRIPTION: This snippet demonstrates how to use the `arrappend` method provided by a Redis client library in TypeScript. It appends the value 'a' to the JSON array located at the specified path '$.path.to.array' within the document identified by the key 'key'. This is an asynchronous operation. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/arrappend.mdx#_snippet_0 LANGUAGE: ts CODE: ``` await redis.json.arrappend("key", "$.path.to.array", "a"); ``` ---------------------------------------- TITLE: Calling JSON.ARRINDEX Command in TypeScript DESCRIPTION: This snippet demonstrates how to use the redis.json.arrindex method provided by a TypeScript Redis client. It calls the command with the key "key", the path "$.path.to.array", and the value "a" to find the index of the first occurrence of "a" in the specified array. The result is awaited and stored in the `index` variable. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/arrindex.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` const index = await redis.json.arrindex("key", "$.path.to.array", "a"); ``` ---------------------------------------- TITLE: Using Redis SPOP in Python (With Count) DESCRIPTION: Shows how to use the SPOP command with the 'count' argument in Python to remove and return multiple random members from a Redis set. It adds members to the set and then calls SPOP with a count of 2, asserting the result. Requires a connected Redis client. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/set/spop.mdx#_snippet_1 LANGUAGE: python CODE: ``` redis.sadd("myset", "one", "two", "three") assert redis.spop("myset", 2) in {"one", "two", "three"} ``` ---------------------------------------- TITLE: Getting JSON Array Length using Redis Python Client DESCRIPTION: This snippet demonstrates how to call the `arrlen` command using the RedisBloom Python client's JSON module. It takes the Redis key name and the JSON path to the array as input, returning the integer length of the array at that path. The result is stored in the `length` variable. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/json/arrlen.mdx#_snippet_0 LANGUAGE: python CODE: ``` length = redis.json.arrlen("key", "$.path.to.array") ``` ---------------------------------------- TITLE: Flushing Redis Script Cache Asynchronously in Python DESCRIPTION: This snippet demonstrates how to call the SCRIPT FLUSH command using a Python Redis client instance. It removes all previously loaded Lua scripts from the Redis server's script cache. The "flush_type" parameter is set to "ASYNC" to request an asynchronous flush operation, which is generally preferred for performance. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/scripts/script_flush.mdx#_snippet_0 LANGUAGE: python CODE: ``` redis.script_flush(flush_type="ASYNC") ``` ---------------------------------------- TITLE: Trimming JSON Array with Redis JSON (TypeScript) DESCRIPTION: This TypeScript snippet demonstrates how to use the `JSON.ARRTRIM` command via the `redis.json.arrtrim` method. It calls the method on a Redis client instance (`redis`), providing the key ('key'), the JSON path to the array ('$.path.to.array'), the starting index (2), and the stopping index (10) for the trim operation. The awaited result, representing the new length of the array, is stored in the `length` variable. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/json/arrtrim.mdx#_snippet_0 LANGUAGE: typescript CODE: ``` const length = await redis.json.arrtrim("key", "$.path.to.array", 2, 10); ``` ---------------------------------------- TITLE: Using LPUSHX in Python DESCRIPTION: This snippet demonstrates the usage of the Redis `LPUSHX` command with a Python client. It shows how `LPUSHX` successfully adds elements to an existing list and returns the new length, and how it correctly returns 0 and adds no elements when used on a non-existent key. Requires a Redis client library (e.g., `redis-py`). SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/list/lpushx.mdx#_snippet_0 LANGUAGE: python CODE: ``` # Initialize the list redis.lpush("mylist", "one") assert redis.lpushx("mylist", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["three", "two", "one"] # Non existing key assert redis.lpushx("non-existent-list", "one") == 0 ``` ---------------------------------------- TITLE: Aggregating ZINTER with Scores Redis Python DESCRIPTION: Illustrates using ZINTER with the `withscores=True` and `aggregate="SUM"` options in Python. It adds elements to two sets with common members and calculates the sum of scores for these intersecting members, asserting the correct output including member-score tuples. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/py/commands/zset/zinter.mdx#_snippet_1 LANGUAGE: python CODE: ``` redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zinter(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ``` ---------------------------------------- TITLE: Creating New Azure Function from Template - Shell DESCRIPTION: This command creates a new Azure Function file based on a predefined template. It names the function 'CounterFunction', uses the 'HTTP trigger' template, and sets the authentication level to 'anonymous', allowing unauthenticated access. SOURCE: https://github.com/upstash/docs/blob/main/redis/quickstarts/azure-functions.mdx#_snippet_2 LANGUAGE: shell CODE: ``` func new --name CounterFunction --template "HTTP trigger" --authlevel "anonymous" ``` ---------------------------------------- TITLE: Storing Redis Sorted Set Intersection (Aggregate) - TypeScript DESCRIPTION: This snippet demonstrates using the 'aggregate' option with zinterstore, specifically setting it to 'sum'. It populates two sorted sets and then calculates their intersection, storing the output in 'destination'. For members present in both sets, their scores are combined according to the 'sum' aggregation rule before being assigned to the member in the destination set. The number of elements in the resulting set is logged. SOURCE: https://github.com/upstash/docs/blob/main/redis/sdks/ts/commands/zset/zinterstore.mdx#_snippet_2 LANGUAGE: ts CODE: ``` await redis.zadd( "key1", { score: 1, member: "member1" }, ) await redis.zadd( "key2", { score: 1, member: "member1" }, { score: 2, member: "member2" }, ) const res = await redis.zinterstore( "destination", 2, ["key1", "key2"], { aggregate: "sum" }, ); console.log(res) // 1 ```