### Install Ratelimit package Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted Commands to install the Upstash Ratelimit library for different environments. ```bash npm install @upstash/ratelimit ``` ```ts import { Ratelimit } from "https://cdn.skypack.dev/@upstash/ratelimit@latest"; ``` -------------------------------- ### Configure environment variables Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted Commands and file formats for setting up required Upstash credentials in different development environments. ```bash npx wrangler secret put UPSTASH_REDIS_REST_URL npx wrangler secret put UPSTASH_REDIS_REST_TOKEN ``` ```text UPSTASH_REDIS_REST_URL=**** UPSTASH_REDIS_REST_TOKEN=**** ``` -------------------------------- ### Initialize and implement Ratelimit Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted Demonstrates how to initialize the Ratelimit instance using Redis and apply it to an endpoint to control request flow based on a sliding window algorithm. ```ts import { Ratelimit } from "@upstash/ratelimit"; import { Redis } from "@upstash/redis"; const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), analytics: true, prefix: "@upstash/ratelimit", }); const identifier = "api"; const { success } = await ratelimit.limit(identifier); if (!success) { return "Unable to process at this time"; } doExpensiveCalculation(); return "Here you go!"; ``` -------------------------------- ### Manual Redis client initialization Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted Shows how to manually instantiate the Redis client by providing the URL and token directly, bypassing environment variable auto-detection. ```ts new Redis({ url: "https://****.upstash.io", token: "********", }); ``` -------------------------------- ### Run Flask Application Source: https://upstash.com/docs/redis/overall/llms-txt Starts the Flask development server for the Redis-backed application. ```APIDOC ## Run Flask Application ### Description Starts the Flask development server for the Redis-backed application. ### Method Shell Command ### Endpoint N/A ### Parameters - None ### Request Example ```bash python app.py ``` ### Response - N/A (Server output will be displayed in the console) ### Notes This command assumes app.py is in the current directory and Flask is installed. ``` -------------------------------- ### Evaluate Lua Script (GET example) Source: https://upstash.com/docs/redis/overall/llms-txt Evaluates a Lua script that retrieves a key's value. ```APIDOC ## Evaluate Lua Script (GET example) ### Description Evaluates a Lua script that retrieves a key's value. ### Method POST ### Endpoint /api/redis/eval ### Parameters #### Request Body - **script** (string) - Required - The Lua script to execute. - **keys** (string[]) - Required - An array of keys the script needs. ### Request Example ```json { "script": "local value = redis.call(\"GET\", KEYS[1])\nreturn value", "keys": ["mykey"] } ``` ### Response #### Success Response (200) - **result** (any) - The result of the script execution. #### Response Example ```json { "result": "Hello" } ``` ``` -------------------------------- ### Initialize Node.js Project and Dependencies Source: https://upstash.com/docs/redis/howto/getstartedawslambda Commands to initialize a new Node.js project and install the ioredis client dependency. ```bash npm init npm install ioredis ``` -------------------------------- ### Setup Laravel Project Source: https://upstash.com/docs/redis/overall/llms-txt Installs the Laravel installer globally and scaffolds a new project named 'example-app'. ```shell composer global require laravel/installer laravel new example-app cd example-app ``` -------------------------------- ### Python Example for ZPOPMAX Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the ZPOPMAX command in Python. It demonstrates adding elements to a sorted set and then asserting the correct retrieval of the highest-scoring member. ```APIDOC ## Python Example for ZPOPMAX ### Description Illustrates how to use the ZPOPMAX command in Python. It demonstrates adding elements to a sorted set and then asserting the correct retrieval of the highest-scoring member. ### Method Not applicable (SDK example) ### Endpoint Not applicable (SDK example) ### Parameters Not applicable (SDK example) ### Request Example ```py redis.zadd("myset", {"a": 1, "b": 2, "c": 3}) assert redis.zpopmax("myset") == [("c", 3)] ``` ### Response #### Success Response Returns the member with the highest score and its score. If the set is empty, returns an empty list. #### Response Example ```json [["c", 3]] ``` ``` -------------------------------- ### Uvicorn Command Source: https://upstash.com/docs/redis/overall/llms-txt Starts a FastAPI application using Uvicorn with live reloading. ```APIDOC ## Uvicorn Command ### Description Starts a FastAPI application using Uvicorn with live reloading. ### Method N/A (Shell Command) ### Endpoint N/A (Shell Command) ### Parameters N/A (Shell Command) ### Request Example ```shell uvicorn main:app --reload ``` ### Response N/A (Shell Command) ``` -------------------------------- ### Initialize Node.js Project and Install ioredis (npm) Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Node.js project and installs the 'ioredis' client. This is a common setup step for Node.js applications interacting with Redis. ```bash npm init npm install ioredis ``` -------------------------------- ### LTRIM Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Trims a list so that only elements with indices between the given start and stop are kept. ```APIDOC ## LTRIM Command Example in Python ### Description Trims a list so that only elements with indices between the given start and stop are kept. ### Method `redis.ltrim(key, start, stop)` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters - **key** (str) - Required - The key of the list. - **start** (int) - Required - The starting index. - **stop** (int) - Required - The ending index. ### Request Example ```python redis.rpush("mylist", "one", "two", "three") redis.ltrim("mylist", 0, 1) ``` ### Response #### Success Response (200) - **bool** - Returns True if the trim operation was successful. #### Response Example ```json True ``` ``` -------------------------------- ### Upstash REST API URL mapping for Redis commands (Bash) Source: https://upstash.com/docs/redis/overall/llms-txt Provides examples of how various Redis commands are translated into URL paths for the Upstash REST API. This is useful for making direct HTTP requests to a Redis instance without using a client library. Examples cover SET, GET, MGET, HGET, and ZADD commands. ```bash - `SET foo bar` -> `REST_URL/set/foo/bar` - `SET foo bar EX 100` -> `REST_URL/set/foo/bar/EX/100` - `GET foo` -> `REST_URL/get/foo` - `MGET foo1 foo2 foo3` -> `REST_URL/mget/foo1/foo2/foo3` - `HGET employee:23381 salary` -> `REST_URL/hget/employee:23381/salary` - `ZADD teams 100 team-x 90 team-y` -> `REST_URL/zadd/teams/100/team-x/90/team-y` ``` -------------------------------- ### Run Django development server Source: https://upstash.com/docs/redis/quickstarts/django Command to start the local development server to test the Redis-backed counter functionality. ```shell python manage.py runserver ``` -------------------------------- ### Install Upstash Redis and Django dependencies Source: https://upstash.com/docs/redis/quickstarts/django Commands to install the necessary Python packages for Django and the Upstash Redis client. ```shell pip install django pip install upstash-redis ``` -------------------------------- ### Install Celery with Redis Support Source: https://upstash.com/docs/redis/overall/llms-txt Installs the Celery library with the necessary Redis integration for use as a message broker and result backend. ```APIDOC ## Install Celery with Redis Support ### Description Installs the Celery library with the necessary Redis integration for use as a message broker and result backend. This command uses pip to manage Python packages. ### Method CLI Command ### Endpoint N/A ### Parameters #### Command Line Arguments - **package** (string) - Required - The package to install. ### Request Example ```bash pip install "celery[redis]" ``` ### Response N/A (CLI Output) ``` -------------------------------- ### Get Stream Length (XLEN) API Example Source: https://upstash.com/docs/redis/overall/llms-txt Provides an API example for the XLEN command, which returns the number of entries in a Redis stream. It specifies the GET method and the endpoint, along with query parameters and the expected JSON response structure. ```http GET /websites/upstash-redis/xlen?key=mystream ``` -------------------------------- ### Create Project Directory via Shell Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates standard shell commands to create a new project directory and navigate into it, serving as a foundational setup step. ```bash mkdir cloud-run-sessions cd cloud-run-sessions ``` -------------------------------- ### Dockerfile CMD Instruction for Node.js Source: https://upstash.com/docs/redis/overall/llms-txt Example CMD instruction for a Dockerfile to run a Node.js application. It specifies 'npm start' as the command to execute when a container is initiated. ```dockerfile CMD [ "npm", "start" ] ``` -------------------------------- ### Get list length with LLEN in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to retrieve the number of elements in a Redis list using the LLEN command. Includes an example of populating the list before measurement. ```typescript await redis.rpush("key", "a", "b", "c"); const length = await redis.llen("key"); console.log(length); ``` -------------------------------- ### Execute Redis GET command Source: https://upstash.com/docs/redis/overall/llms-txt A basic representation of the Redis GET command used to retrieve values from the store. ```redis GET ``` -------------------------------- ### Python ZINCRBY Example Source: https://upstash.com/docs/redis/overall/llms-txt This example demonstrates how to use the `zincrby` command in Python to increment the score of a member in a sorted set. ```APIDOC ## Python ZINCRBY Example ### Description This example demonstrates how to use the `zincrby` command in Python to increment the score of a member in a sorted set. ### Method `ZINCRBY` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters - **key** (str) - Required - The key of the sorted set. - **increment** (float | int) - Required - The amount to increment the score by. - **member** (str) - Required - The member whose score is to be incremented. ### Request Example ```python redis.zadd("myset", {"one": 1, "two": 2, "three": 3}) assert redis.zincrby("myset", 2, "one") == 3 ``` ### Response #### Success Response (200) - **(float | int)** - The new score of the member. ``` -------------------------------- ### TTL /api/redis/ttl Source: https://upstash.com/docs/redis/overall/llms-txt Get the time to live for a key. ```APIDOC ## TTL /api/redis/ttl ### Description Get the time to live for a key. ### Method TTL ### Endpoint /api/redis/ttl ### Parameters #### Path Parameters - **key** (string) - Required - The key to get the time to live for. ### Request Example ```json { "key": "mykey" } ``` ### Response #### Success Response (200) - **seconds** (integer) - The time to live in seconds, or -1 if the key has no expiration, or -2 if the key does not exist. #### Response Example ```json { "seconds": 60 } ``` ``` -------------------------------- ### Get Value from Upstash Redis (Python API Example) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to retrieve the value associated with a given key from Upstash Redis using a Python client. The example includes setting a key-value pair and then fetching its value, asserting the correct retrieval. ```python # Example theme={"system"} redis.set("key", "value") assert redis.get("key") == "value" ``` -------------------------------- ### Install Redis and Histogram dependencies Source: https://upstash.com/docs/redis/overall/llms-txt Commands to install essential Node.js packages for interacting with Upstash Redis and handling histogram data. ```bash npm install ioredis npm install hdr-histogram-js ``` -------------------------------- ### Upstash Redis with Cloudflare Workers in JavaScript Source: https://upstash.com/docs/redis/overall/llms-txt Example demonstrating how to use Upstash Redis with Cloudflare Workers for low-latency data access at the edge. It shows setting and getting data within the worker's fetch handler. ```javascript import { Redis } from '@upstash/redis'; const redis = new Redis({ url: env.REDIS_URL, token: env.REDIS_TOKEN, }); export default { async fetch(request, env) { // Example: Setting a key await redis.set('edge_data', 'hello from the edge'); // Example: Getting a key const data = await redis.get('edge_data'); return new Response(data); }, }; ``` -------------------------------- ### Initialize Django project and application Source: https://upstash.com/docs/redis/quickstarts/django Standard Django commands to scaffold a new project and a specific application module. ```shell django-admin startproject myproject cd myproject python manage.py startapp myapp ``` -------------------------------- ### Install Dependencies for FastAPI and Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary Python packages for building a FastAPI application with Upstash Redis caching. ```APIDOC ## Install Dependencies for FastAPI and Upstash Redis ### Description Installs the necessary Python packages for building a FastAPI application with Upstash Redis caching. This includes the FastAPI framework, the Upstash Redis client, and a Uvicorn ASGI server. ### Method CLI Command ### Endpoint N/A ### Parameters #### Command Line Arguments - **package** (string) - Required - The package to install. ### Request Example ```shell pip install fastapi upstash-redis uvicorn[standard] ``` ### Response N/A (CLI Output) ``` -------------------------------- ### Configure package.json Start Script Source: https://upstash.com/docs/redis/overall/llms-txt Defines the application start command within the package.json file. ```json { "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index" } } ``` -------------------------------- ### SCARD - Get Set Size API Request Example Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to get the number of elements in a set stored at a specific key using the SCARD command. The key is provided as a query parameter. ```bash GET /SCARD?key=my_set ``` -------------------------------- ### Evaluate Lua Script (ARGV example) Source: https://upstash.com/docs/redis/overall/llms-txt Evaluates a Lua script and passes arguments to it. ```APIDOC ## Evaluate Lua Script (ARGV example) ### Description Evaluates a Lua script and passes arguments to it. ### Method POST ### Endpoint /api/redis/eval ### Parameters #### Request Body - **script** (string) - Required - The Lua script to execute. - **args** (string[]) - Required - An array of arguments to pass to the script. ### Request Example ```json { "script": "return ARGV[1]", "args": ["Hello"] } ``` ### Response #### Success Response (200) - **result** (any) - The result of the script execution. #### Response Example ```json { "result": "Hello" } ``` ``` -------------------------------- ### Install Laravel Installer and Create Project Source: https://upstash.com/docs/redis/quickstarts/laravel Installs the Laravel installer globally using Composer and then creates a new Laravel project named 'example-app'. This is the initial step for setting up a new Laravel application. ```shell composer global require laravel/installer laravel new example-app cd example-app ``` -------------------------------- ### PTTL /api/redis/pttl Source: https://upstash.com/docs/redis/overall/llms-txt Get the time to live for a key in milliseconds. ```APIDOC ## PTTL /api/redis/pttl ### Description Get the time to live for a key in milliseconds. ### Method PTTL ### Endpoint /api/redis/pttl ### Parameters #### Path Parameters - **key** (string) - Required - The key to get the time to live for. ### Request Example { "key": "mykey" } ### Response #### Success Response (200) - **milliseconds** (integer) - The time to live in milliseconds, or -1 if the key has no expiration, or -2 if the key does not exist. #### Response Example { "milliseconds": 50000 } ``` -------------------------------- ### TypeScript JSON.GET Usage Examples Source: https://upstash.com/docs/redis/overall/llms-txt Examples demonstrating `redis.json.get` in TypeScript for retrieving values from JSON documents. Covers basic path-based retrieval and advanced usage with formatting options. ```APIDOC ## TypeScript JSON.GET Usage Examples ### Description Examples demonstrating `redis.json.get` in TypeScript for retrieving values from JSON documents. Covers basic path-based retrieval and advanced usage with formatting options like indentation, newlines, and spaces. ### Method TypeScript Code ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript const value = await redis.json.get("key", "$.path.to.somewhere"); ``` ```typescript const value = await redis.json.get("key", { indent: " ", newline: "\n", space: " " }, "$.path.to.somewhere"); ``` ### Response #### Success Response - **value** (any) - The JSON value retrieved from the specified path. #### Response Example ```json "some_value" ``` ``` -------------------------------- ### Serverless Project Setup with npm Source: https://upstash.com/docs/redis/tutorials/auto_complete_with_serverless_redis Commands to set up a new Node.js project using the Serverless Framework and install the ioredis client. This prepares the environment for building the autocomplete API. ```bash npm install -g serverless serverless npm init npm install ioredis ``` -------------------------------- ### Create Demo Application Directory and Initialize npm Source: https://upstash.com/docs/redis/overall/llms-txt Sets up a new project directory for a demo application and initializes a package.json file using npm. These bash commands are the first steps in creating a Node.js application. ```bash mkdir example-koyeb-upstash cd example-koyeb-upstash ``` ```bash npm init -y ``` -------------------------------- ### GET /get - Get Histogram API Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the histogram data for a specified test name using a GET request. ```APIDOC ## GET /get ### Description Retrieves the histogram data for a given test name. ### Method GET ### Endpoint https://v7xx4aa2ib.execute-api.us-east-1.amazonaws.com/get ### Parameters #### Path Parameters None #### Query Parameters - **name** (string) - Required - The name of the test to retrieve histogram data for. #### Request Body None ### Request Example ``` curl https://v7xx4aa2ib.execute-api.us-east-1.amazonaws.com/get?name=perf-test-1 ``` ### Response #### Success Response (200) - **histogram** (object) - An object representing the histogram data. #### Response Example ```json { "histogram": { "90": 1, "80": 1, "34": 1, "97": 1, "93": 1, "45": 1, "49": 1, "57": 1, "99": 1, "12": 1 } } ``` ``` -------------------------------- ### Install Flask and Upstash Redis Client (Python) Source: https://upstash.com/docs/redis/quickstarts/flask Installs the necessary Python packages for Flask and the Upstash Redis client. Ensure you have pip installed. ```shell pip install flask pip install upstash-redis ``` -------------------------------- ### GET /redis/get Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the value associated with the specified key. ```APIDOC ## GET /redis/get ### Description Return the value of the specified key or `None` if the key doesn't exist. ### Method GET ### Parameters #### Query Parameters - **key** (string) - Required - The key to retrieve. ### Response #### Success Response (200) - **value** (any) - The value stored at the key or `None`. ``` -------------------------------- ### Initialize Serverless Framework Project Source: https://upstash.com/docs/redis/overall/llms-txt Guides the user through the interactive CLI process to scaffold a new Serverless project. It supports selecting templates, runtimes, and naming the service for AWS Node.js environments. ```text serverless # Follow interactive prompts to select AWS / Node.js / HTTP API template ``` -------------------------------- ### Project Setup Commands (Bash) Source: https://upstash.com/docs/redis/tutorials/aws_app_runner_with_redis These bash commands outline the initial steps for setting up a Node.js project intended for deployment with AWS App Runner and Upstash Redis. It includes creating a project directory, initializing a Node.js project, and installing the 'ioredis' package. ```bash mkdir app_runner_example cd app_runner_example npm init npm install ioredis ``` -------------------------------- ### Deno Initialization Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to initialize an Upstash Redis client in Deno environments. ```APIDOC ## Initialize Upstash Redis in Deno ### Description Initializes an Upstash Redis client in Deno environments, including Deno Deploy and Netlify Edge. ### Usage ```ts import { Redis } from "https://deno.land/x/upstash_redis/mod.ts" const redis = new Redis({ url: "", token: "", }) ``` ``` -------------------------------- ### Configure Redis for edge runtimes Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted Specific import configurations required for running Upstash Redis on Cloudflare Workers or Fastly Compute@Edge. ```ts import { Redis } from "@upstash/redis/cloudflare"; import { Redis } from "@upstash/redis/fastly"; ``` -------------------------------- ### Install Upstash Redis with Next.js Pages Router Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary packages for a Next.js application using the Pages Router and the Upstash Redis client. ```APIDOC ## Install Upstash Redis with Next.js Pages Router ### Description Installs the necessary packages for a Next.js application using the Pages Router and the Upstash Redis client. ### Command ```shell npx create-next-app@latest cd my-app npm install @upstash/redis ``` ``` -------------------------------- ### Get Random Hash Field with Python Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to retrieve a single random field from a Redis hash using the `HRANDFIELD` command in Python. This example assumes a Redis client instance is already set up and a hash named 'myhash' exists. ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hrandfield("myhash") in ["field1", "field2"] ``` -------------------------------- ### Create Demo Application Directory and Initialize npm Source: https://upstash.com/docs/redis/quickstarts/koyeb These bash commands set up a new project directory for the demo application and initialize a package.json file using npm. This is the first step in creating the Node.js application. ```bash mkdir example-koyeb-upstash cd example-koyeb-upstash ``` ```bash npm init -y ``` -------------------------------- ### Initialize Laravel project Source: https://upstash.com/docs/redis/overall/llms-txt Commands to create a new Laravel project using either the Laravel CLI or Composer. ```shell laravel new example-app cd example-app ``` ```shell composer create-project laravel/laravel example-app cd example-app ``` -------------------------------- ### Install HTTPoison Dependency for Elixir Source: https://upstash.com/docs/redis/overall/llms-txt Instructions for fetching the HTTPoison library dependency in an Elixir project using the mix build tool. ```bash mix deps.get ``` -------------------------------- ### Strapi Plugin Configuration Source: https://upstash.com/docs/redis/overall/llms-txt JSON configuration example to enable or disable the Upstash Ratelimit plugin for Strapi. ```json { "enabled": false } ``` -------------------------------- ### Serverless Project Setup with npm Source: https://upstash.com/docs/redis/overall/llms-txt Commands to set up a new Node.js project using the Serverless Framework and install the ioredis client. This prepares the environment for building serverless APIs. ```bash npm install -g serverless serverless npm init npm install ioredis ``` -------------------------------- ### Create a basic search index Source: https://upstash.com/docs/redis/search/index-management Demonstrates how to initialize a search index with a specific prefix and schema. Supports string data types and allows skipping initial scans of existing keys. ```typescript const profiles = await redis.search.createIndex({ name: "profiles", dataType: "string", prefix: "profiles:", skipInitialScan: true, schema: s.object({ name: s.string(), }), }); ``` ```python profiles = redis.search.create_index( name="profiles", data_type="string", prefixes="profiles:", skip_initial_scan=True, schema={ "name": "TEXT", }, ) ``` ```bash SEARCH.CREATE profiles ON STRING PREFIX 1 profiles: SKIPINITIALSCAN SCHEMA name TEXT ``` -------------------------------- ### Run Flask Application (Shell) Source: https://upstash.com/docs/redis/quickstarts/flask Executes the Flask application locally. This command starts the development server, typically on http://127.0.0.1:5000/. ```shell python app.py ``` -------------------------------- ### Create New Laravel Project Source: https://upstash.com/docs/redis/overall/llms-txt Creates a new Laravel project named 'example-app' using the Laravel CLI and navigates into the project directory. This requires the Laravel installer to be set up. ```shell laravel new example-app cd example-app ``` -------------------------------- ### Install FastAPI and Upstash Rate Limiting Dependencies Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary Python packages for building a FastAPI application with Upstash Redis for rate limiting, including the ASGI server Uvicorn. ```APIDOC ## Install FastAPI and Upstash Rate Limiting Dependencies ### Description Installs Python packages required for a FastAPI application with Upstash Redis rate limiting. ### Command ```shell pip install fastapi upstash-redis upstash-ratelimit uvicorn[standard] ``` ``` -------------------------------- ### ZINTER with Weights Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Compute the intersection of two sorted sets with custom weights and aggregation. ```APIDOC ## ZINTER with Weights Example (Python) ### Description Compute the intersection of two sorted sets with custom weights and aggregation. ### Method APICALL ### Endpoint /redis/zinter ### Parameters #### Query Parameters - **keys** (string[]) - Required - The keys of the sorted sets to intersect. - **withscores** (boolean) - Optional - Whether to return scores along with members. - **aggregate** (string) - Optional - The aggregation method (e.g., 'SUM', 'MIN', 'MAX'). - **weights** (number[]) - Optional - The weights to apply to each key. ### Request Example ```json { "keys": ["key1", "key2"], "withscores": true, "aggregate": "SUM", "weights": [2, 3] } ``` ### Response #### Success Response (200) - **Result** (Array<[string, number]>) - An array of members and their scores in the intersection. #### Response Example ```json [["a", 5]] ``` ``` -------------------------------- ### Install Node.js Dependencies for Express Session Source: https://upstash.com/docs/redis/overall/llms-txt Installs the required npm packages for managing Express sessions with Redis, including the core express, redis, and connect-redis libraries. ```bash npm install express redis connect-redis express-session ``` -------------------------------- ### Initialize Next.js project and install Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Commands to scaffold a new Next.js application and install the required @upstash/redis SDK dependency. ```shell npx create-next-app@latest cd my-app npm install @upstash/redis ``` -------------------------------- ### SMISMEMBER Command Source: https://upstash.com/docs/redis/overall/llms-txt Information for the SMISMEMBER command. No specific description or usage examples were provided. ```APIDOC ## SMISMEMBER Command ### Description No description provided. ### Method POST (Implied by command format) ### Endpoint /redis/v1/command (Implied by context) ### Request Body Example ```json { "command": "SMISMEMBER", "key": "your_set_key", "members": ["member1", "member2"] } ``` ### Response Example ```json { "result": [1, 0] } ``` ``` -------------------------------- ### Initialize Fastly Compute project Source: https://upstash.com/docs/redis/overall/llms-txt Provides the CLI command sequence to initialize a new Fastly Compute@Edge project using the JavaScript empty starter template. ```shell > fastly compute init Creating a new Compute@Edge project. Press ^C at any time to quit. Name: [fastly-upstash] Description: Author: [enes@upstash.com] Language: [1] Rust [2] JavaScript [3] AssemblyScript (beta) [4] Other ('bring your own' Wasm binary) Choose option: [1] 2 Starter kit: [1] Default starter for JavaScript A basic starter kit that demonstrates routing, simple synthetic responses and overriding caching rules. https://github.com/fastly/compute-starter-kit-javascript-default [2] Empty starter for JavaScript An empty application template for the Fastly Compute@Edge environment which simply returns a 200 OK response. https://github.com/fastly/compute-starter-kit-javascript-empty Choose option or paste git URL: [1] 2 ``` -------------------------------- ### Install Node.js Dependencies for Redis and Histogram Source: https://upstash.com/docs/redis/overall/llms-txt Provides shell commands to install the 'ioredis' package for Redis client functionality and 'hdr-histogram-js' for histogram data manipulation using npm. ```shell npm install ioredis npm install hdr-histogram-js ``` -------------------------------- ### Install and Use upstash-redis-dump Source: https://upstash.com/docs/redis/overall/llms-txt Commands to install the Go-based dump tool and perform data migration between Redis instances. ```bash go install github.com/upstash/upstash-redis-dump@latest ``` ```bash upstash-redis-dump -db 0 -host YOUR_REGIONAL_HOST -port YOUR_DATABASE_PORT -pass YOUR_PASSWORD -tls > redis.dump ``` ```bash redis-cli --tls -u redis://YOUR_PASSWORD@YOUR_REGIONAL_HOST:6379 --pipe < redis.dump ``` -------------------------------- ### Initialize Fastly Compute Project Source: https://upstash.com/docs/redis/overall/llms-txt CLI commands to bootstrap a new Fastly Compute project and install the required Upstash Redis SDK. ```shell fastly compute init npm install @upstash/redis ``` -------------------------------- ### LPUSHX Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use the `lpushx` command in TypeScript to prepend an element to a list only if the list already exists. This example first ensures a list exists using `lpush` and then demonstrates `lpushx`, logging the new list length. ```APIDOC ## LPUSHX Command Example ### Description Prepends an element to a list, but only if the list exists. ### Method N/A (Redis Command) ### Endpoint N/A (Redis Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' is an initialized Upstash Redis client await redis.lpush("key", "a", "b", "c"); const length = await redis.lpushx("key", "d"); console.log(length); // 4 ``` ### Response #### Success Response (200) - **length** (number) - The length of the list after the push operation. #### Response Example ```json 4 ``` ``` -------------------------------- ### Initialize Nuxt.js Project and Install Upstash Redis SDK Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Nuxt.js project using the Nuxt CLI and installs the `@upstash/redis` package. This sets up a basic Nuxt application with Redis connectivity. ```bash npx nuxi@latest init nuxtjs-with-redis npm install @upstash/redis ``` -------------------------------- ### ZADD and ZLEXCOUNT Example in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt This example demonstrates how to add elements to a sorted set using ZADD and then count elements within a lexicographical range using ZLEXCOUNT in TypeScript. ```APIDOC ## ZADD and ZLEXCOUNT Example in TypeScript ### Description This example demonstrates how to add elements to a sorted set using ZADD and then count elements within a lexicographical range using ZLEXCOUNT in TypeScript. It requires the Upstash Redis client library. ### Method TypeScript Code ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" }, ); const elements = await redis.zlexcount("key", "two", "+"); console.log(elements); // 1 ``` ### Response #### Success Response - **elements** (number) - The number of elements in the specified lexicographical range. #### Response Example ```json 1 ``` ``` -------------------------------- ### Python SDIFF Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `SDIFF` command in Python with the Upstash Redis client. It demonstrates adding elements to two sets and then asserting the correct difference between them. ```python redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); assert redis.sdiff("set1", "set2") == {"a", "b"} ``` -------------------------------- ### Initialize Project and Dependencies Source: https://upstash.com/docs/redis/overall/llms-txt Commands for initializing a new Node.js project or installing specific Upstash plugins via package managers. ```Bash npm init -y ``` ```npm npm install --save @upstash/strapi-plugin-upstash-ratelimit ``` ```yarn yarn add @upstash/strapi-plugin-upstash-ratelimit ``` -------------------------------- ### GET /randomkey Source: https://upstash.com/docs/redis/overall/llms-txt Fetches a random key from the Upstash Redis database. ```APIDOC ## GET /randomkey ### Description Fetches a random key from your Upstash Redis database using the `randomkey` command. ### Method GET ### Request Example ```typescript const key = await redis.randomkey(); ``` ``` -------------------------------- ### Initialize Redis client Source: https://upstash.com/docs/redis/quickstarts/nextjs-app-router Creates a reusable Redis client instance using environment variables, exported from a central library file. ```typescript import { Redis } from "@upstash/redis" export const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN, }) ``` -------------------------------- ### Add Start Script to package.json (Node.js) Source: https://upstash.com/docs/redis/tutorials/cloud_run_sessions Configures the 'start' script in the 'package.json' file to run the Node.js application using the 'node index' command. This is a standard practice for defining how to start the application. ```json { "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node index" } } ``` -------------------------------- ### CONFIG GET notify-keyspace-events Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the current value of the `notify-keyspace-events` option using `CONFIG GET` to verify keyspace and keyevent notification configurations. ```APIDOC ## CONFIG GET notify-keyspace-events ### Description Retrieves the current configuration for Redis keyspace notifications. ### Method POST ### Endpoint `$UPSTASH_REDIS_REST_URL` ### Parameters #### Request Body - **command** (List[str]) - Required - Should be `["CONFIG", "GET", "notify-keyspace-events"]` ### Request Example ```json ["CONFIG", "GET", "notify-keyspace-events"] ``` ### Response #### Success Response (200) - **response** (List[str]) - Description: A list containing the configuration key and its value, e.g., `["notify-keyspace-events", "gKEA"]` #### Error Response (e.g., 400, 401, 404) - **error** (string) - Description: An error message indicating the issue. ``` -------------------------------- ### Install Serverless Framework (npm) Source: https://upstash.com/docs/redis/tutorials/serverless_java_redis Installs the Serverless Framework globally using npm. This is a prerequisite for deploying serverless applications. ```shell npm i serverless@3.39.0 -g ``` -------------------------------- ### Define Dockerfile for Application Source: https://upstash.com/docs/redis/overall/llms-txt Provides standard Dockerfile instructions to copy local source code into a container and define the startup command using npm. ```Dockerfile COPY . ./ CMD [ "npm", "start" ] ``` -------------------------------- ### Python JSON.SET Example with NX Option Source: https://upstash.com/docs/redis/overall/llms-txt This example demonstrates using the `nx=true` option with the `redis.json.set` command to conditionally set a JSON value only if the specified path does not already exist. ```APIDOC ## Python JSON.SET Example with NX Option ### Description This example demonstrates using the `nx=true` option with the `redis.json.set` command to conditionally set a JSON value only if the specified path does not already exist. ### Method `JSON.SET` ### Arguments #### Path Parameters - **key** (str) - Required - The key of the JSON document. - **path** (str) - Required - The JSON path to set the value. - **value** (any) - Required - The JSON value to set. - **nx** (bool) - Optional - If true, only set the key if the path does not already exist. ### Request Example ```python value = ... # Define the value to set redis.json.set(key, "$.path", value, nx=True) ``` ``` -------------------------------- ### HPEXPIRETIME Usage Example Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the expiration time in milliseconds of a field in a hash. ```APIDOC ## HPEXPIRETIME ### Description Retrieves the expiration time in milliseconds of a field in a hash. ### Method N/A (Redis Command) ### Endpoint N/A (Redis Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' is an initialized Upstash Redis client await redis.hset("my-key", "my-field", "my-value"); await redis.hpexpireat("my-key", "my-field", Date.now() + 1000); const expireTime = await redis.hpexpiretime("my-key", "my-field"); console.log(expireTime); // e.g., 1697059200000 ``` ### Response #### Success Response (200) - **expireTime** (number | null) - The expiration time in milliseconds, or null if the field does not exist or has no expiration. ``` -------------------------------- ### Cloudflare Worker Local Development Source: https://upstash.com/docs/redis/overall/llms-txt Command to start a local development server for Cloudflare Workers. ```APIDOC ## Run Cloudflare Worker Locally ### Description Starts a local development server for the Cloudflare Worker using `npx wrangler dev`, allowing for testing and debugging the worker's functionality before deployment. ### Method Shell Command ### Endpoint N/A ### Request Example ```shell npx wrangler dev ``` ``` -------------------------------- ### ZRANGE Command Examples with Python Source: https://upstash.com/docs/redis/overall/llms-txt Covers various ZRANGE operations including basic retrieval, reverse ordering, sorting by score, and including scores in the output. ```python import redis redis_client = redis.Redis(host='YOUR_REDIS_HOST', port=YOUR_REDIS_PORT, password='YOUR_REDIS_PASSWORD') # Example 1: Basic ZRANGE redis_client.zadd("myset", {"a": 1, "b": 2, "c": 3}) print(f"Basic ZRANGE: {redis_client.zrange('myset', 0, 1)}") # Example 2: ZRANGE with reverse order print(f"Reverse ZRANGE: {redis_client.zrange('myset', 0, 1, rev=True)}") # Example 3: ZRANGE sorted by score print(f"Sorted ZRANGE: {redis_client.zrange('myset', 0, 1, sortby='BYSCORE')}") # Example 4: ZRANGE with scores print(f"Zrange with scores: {redis_client.zrange('myset', 0, 1, withscores=True)}") ``` -------------------------------- ### Install Upstash Rate Limiter with Pip Source: https://upstash.com/docs/redis/sdks/ratelimit-py/gettingstarted Installs the `upstash-ratelimit` Python package using pip. This is the first step to integrate Upstash rate limiting into your Python projects. ```bash pip install upstash-ratelimit ``` -------------------------------- ### POST /ratelimit/check Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to set up a fixed window ratelimiter using the upstash_ratelimit library, connected to an Upstash Redis instance. ```APIDOC ## POST /ratelimit/check ### Description Demonstrates how to set up a fixed window ratelimiter using the `upstash_ratelimit` library, connected to an Upstash Redis instance. It configures a limit of 10 requests per 10-second window. ### Method POST ### Endpoint `/ratelimit/check` ### Parameters #### Request Body - **identifier** (string) - Required - A unique identifier for the entity being rate limited (e.g., user ID, IP address). ### Request Example ```python from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), ) # Example usage: # success, remaining_time = ratelimit.take("user_id_123") ``` ### Response #### Success Response (200) - **allowed** (boolean) - Indicates if the request is allowed. - **remaining** (number) - The number of requests remaining within the current window. #### Response Example ```json { "allowed": true, "remaining": 9 } ``` ``` -------------------------------- ### GET /llen Source: https://upstash.com/docs/redis/overall/llms-txt Retrieve the number of elements in a list stored at a specific key. ```APIDOC ## GET /llen ### Description Returns the length of the list stored at key. ### Method GET ### Endpoint /llen ### Parameters #### Query Parameters - **key** (str) - Required - The key of the list. ### Request Example ```http GET /llen?key=my_list ``` ### Response #### Success Response (200) - **length** (int) - The length of the list at key. #### Response Example { "length": 3 } ``` -------------------------------- ### HSET Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Sets multiple fields in a hash stored at a key in Upstash Redis. ```APIDOC ## HSET Command ### Description Sets multiple fields in a hash stored at a key. ### Method POST ### Endpoint /websites/upstash_redis ### Parameters #### Query Parameters - **key** (str) - Required - The key of the hash. #### Request Body - **fields** (object) - Required - An object where keys are field names and values are their corresponding values. ### Request Example ```python redis.hset("myhash", { "field1": "Hello", "field2": "World" }) ``` ### Response #### Success Response (200) - **count** (integer) - The number of fields that were added. #### Response Example ```json { "count": 2 } ``` ``` -------------------------------- ### Run Supabase Function Locally Source: https://upstash.com/docs/redis/overall/llms-txt Starts the Supabase local development environment and serves a specific function for testing. ```APIDOC ## Run Supabase Function Locally ### Description This command starts the Supabase local development environment and serves a specified function locally with options to disable JWT verification and use a custom environment file. ### Command ```bash supabase start supabase functions serve upstash-redis-counter --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.env ``` ``` -------------------------------- ### Initialize Upstash Redis Client from Environment Variables (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to initialize the Upstash Redis client by automatically loading configuration from environment variables and performs a `get` operation. ```APIDOC ## Initialize Upstash Redis Client from Environment Variables (TypeScript) ### Description This TypeScript example shows how to initialize the Upstash Redis client by automatically loading configuration from environment variables (`UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`). It then performs an asynchronous `get` operation to retrieve data from Redis, logging the result or any encountered errors. ### Method TypeScript Code ### Endpoint N/A ### Parameters #### Environment Variables (Required) - **UPSTASH_REDIS_REST_URL** (string) - The URL of the Upstash Redis REST endpoint. - **UPSTASH_REDIS_REST_TOKEN** (string) - The token for authenticating with Upstash Redis. ### Request Example ```typescript 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); } })(); ``` ### Response #### Success Response - **data** (any) - The value retrieved from Redis, or `null` if the key does not exist. #### Response Example ```json "some_value" ``` #### Error Response - **error** (object) - An error object if the operation fails. ``` -------------------------------- ### Create and navigate to demo application directory Source: https://upstash.com/docs/redis/overall/llms-txt Shell commands to create a new directory for a demo application and then change the current working directory into the newly created directory. ```bash mkdir example-koyeb-upstash cd example-koyeb-upstash ``` -------------------------------- ### LRANGE Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the usage of the LRANGE command in Python to fetch elements from a Redis list using positive and negative indices. ```APIDOC ## LRANGE Command Example (Python) ### Description Fetches elements from a Redis list within a specified range. ### Method POST ### Endpoint /websites/upstash_redis ### Parameters #### Query Parameters - **key** (str) - Required - The key of the list. - **start** (integer) - Required - The starting index of the range. - **stop** (integer) - Required - The ending index of the range. ### Request Example ```python redis.rpush("mylist", "one", "two", "three") # Get elements from index 0 to 1 redis.lrange("mylist", 0, 1) # Get all elements redis.lrange("mylist", 0, -1) ``` ### Response #### Success Response (200) - **elements** (array) - An array of elements within the specified range. #### Response Example ```json { "elements": ["one", "two"] } ``` ``` -------------------------------- ### SETRANGE Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the SETRANGE command in Python to overwrite a portion of a string value. ```APIDOC ## SETRANGE Command Example (Python) ### Description Demonstrates the SETRANGE command in Python. It shows setting an initial string value, then overwriting a portion of it using SETRANGE, and finally verifying the updated value. ### Method `SETRANGE` ### Endpoint N/A (Client-side command execution) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```python # Assuming 'redis' is an initialized Redis client instance # Set an initial value for the key redis.set("key", "Hello World") # Use SETRANGE to overwrite starting from index 6 redis.setrange("key", 6, "Redis") # Get the final value of the key redis.get("key") ``` ### Response #### Success Response (200) - **length** (integer) - Returns the new length of the string after modification. #### Response Example ```json 11 ``` ``` -------------------------------- ### Upstash REST API Array Result Example (JSON) Source: https://upstash.com/docs/redis/overall/llms-txt Example of a JSON response from the Upstash REST API when a Redis command returns an array value. ```json { "result": ["value1", null, "value2"] } ``` -------------------------------- ### Install Serverless Framework Source: https://upstash.com/docs/redis/overall/llms-txt Installs the Serverless Framework globally via npm for deployment purposes. ```shell npm i serverless@3.39.0 -g ``` -------------------------------- ### Install and Initialize Cloudflare Workers Project (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Installs the Wrangler CLI globally, logs the user into their Cloudflare account, and generates a new Cloudflare Workers project. Requires Node.js and npm. ```shell npm install -g @cloudflare/wrangler wrangler login wrangler generate edge-leaderboard ``` -------------------------------- ### Upstash REST API Integer Result Example (JSON) Source: https://upstash.com/docs/redis/overall/llms-txt Example of a JSON response from the Upstash REST API when a Redis command returns an integer value. ```json { "result": 137 } ``` -------------------------------- ### Connect to Upstash Redis with Redisson Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to initialize the Redisson client and perform basic operations on a distributed map. ```APIDOC ## Connect to Upstash Redis with Redisson and Perform Basic Operations ### Description This Java code snippet demonstrates how to initialize the Redisson client, connect to an Upstash Redis instance using a password and endpoint, and perform a basic `put` and `get` operation on a distributed map (`RMap`). ### Method N/A (SDK Example) ### Endpoint N/A (SDK Example) ### Parameters None ### Request Example ```Java import org.redisson.Redisson; import org.redisson.api.RMap; import org.redisson.config.Config; public class Main { public static void main(String[] args) { Config config = new Config(); config.useSingleServer().setPassword("YOUR_PASSWORD") .setAddress("YOUR_ENDPOINT"); RedissonClient redisson = Redisson.create(config); RMap map = redisson.getMap("map"); map.put("foo", "bar"); System.out.println(map.get("foo")); } } ``` ### Response N/A (SDK Example) ``` -------------------------------- ### Using Upstash Redis with Remix (JavaScript) Source: https://upstash.com/docs/redis/overall/llms-txt Explains the process of integrating Upstash Redis into Remix applications. This example covers basic Redis operations within the Remix framework using JavaScript. ```javascript import TagFilters from "../../src/components/Filter.js" Using Upstash Redis with Remix ``` -------------------------------- ### Run Supabase Local Development Environment Source: https://upstash.com/docs/redis/overall/llms-txt Starts the local Supabase stack and serves a specific function with environment variables, bypassing JWT verification for local testing. ```bash supabase start supabase functions serve upstash-redis-counter --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.env ``` -------------------------------- ### Python RENAMENX Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the usage of the RENAMENX command in Python. It shows how to rename a key if the destination key does not exist, handling cases where the rename fails due to the destination key already existing. It also verifies the state of keys after successful and failed rename operations. ```APIDOC ## Python RENAMENX Example ### Description Demonstrates the usage of the RENAMENX command in Python. It shows how to rename a key if the destination key does not exist, handling cases where the rename fails due to the destination key already existing. It also verifies the state of keys after successful and failed rename operations. ### Method Not applicable (SDK example) ### Endpoint Not applicable (SDK example) ### Parameters Not applicable (SDK example) ### Request Example ```python 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" ``` ### Response #### Success Response Returns `True` if the rename was successful, `False` otherwise. #### Response Example `True` or `False` ``` -------------------------------- ### GET /pttl Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the expiration time in milliseconds for a given key in Upstash Redis. ```APIDOC ## GET /pttl ### Description Return the expiration in milliseconds of a key. ### Method GET ### Endpoint /pttl ### Parameters #### Query Parameters - **key** (str) - Required - The key whose expiration time needs to be retrieved. ### Response #### Success Response (200) - **expiration_ms** (int) - The number of milliseconds until this expires, negative if the key does not exist or does not have an expiration set. #### Response Example { "expiration_ms": 10000 } #### Error Response (400) - **error** (str) - Description of the error. #### Error Response Example { "error": "Invalid key provided" } ``` -------------------------------- ### Create Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt This snippet demonstrates how to create a new directory for the project and navigate into it using standard shell commands. This is the initial step for setting up the project structure. ```APIDOC ## Create Project Directory ### Description This snippet demonstrates how to create a new directory for the project and navigate into it using standard shell commands. This is the initial step for setting up the project structure. ### Method Shell commands ### Endpoint N/A ### Parameters N/A ### Request Example ```bash mkdir cloud-run-sessions cd cloud-run-sessions ``` ### Response N/A ``` -------------------------------- ### Upstash Redis HVALS Command Example in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using `hset` to populate a Redis hash and then retrieving all its values using the `hvals` command in Python. Includes an assertion for verification. ```APIDOC ## HVALS Command Example (Python) ### Description Sets fields and values in a Redis hash using `hset` and then retrieves all values from that hash using `hvals`. ### Method `HVALS` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) ``` ### Response #### Success Response (200) - **result** (list) - A list containing all the values of the fields in the hash. #### Response Example ```python assert redis.hvals("myhash") == ["Hello", "World"] ``` ``` -------------------------------- ### Java Serverless API Placeholder Source: https://upstash.com/docs/redis/overall/llms-txt A placeholder example for implementing Upstash Redis logic within a Java-based serverless function, such as an AWS Lambda deployment. ```java System.out.println("This is a placeholder for Java code."); ``` -------------------------------- ### GET /get (Serverless API) Source: https://upstash.com/docs/redis/overall/llms-txt Endpoint for retrieving data from the Redis instance via a Serverless function. ```APIDOC ## GET /get ### Description Retrieves data from the Redis store using a serverless function handler. ### Method GET ### Endpoint `/get` ### Response #### Success Response (200) - **result** (string) - The value retrieved from Redis. ``` -------------------------------- ### Connect to Upstash Redis with ioredis (JavaScript) Source: https://upstash.com/docs/redis/overall/llms-txt Example showing how to connect to an Upstash Redis database using the `ioredis` library in Node.js and perform basic set/get operations. -------------------------------- ### TypeScript JSON.GET Examples for Retrieving JSON Data Source: https://upstash.com/docs/redis/overall/llms-txt Examples demonstrating `redis.json.get` in TypeScript for retrieving values from JSON documents stored in Redis. Covers basic path-based retrieval and advanced usage with formatting options. ```typescript const value = await redis.json.get("key", "$.path.to.somewhere"); ``` ```typescript const value = await redis.json.get("key", { indent: " ", newline: "\n", space: " " }, "$.path.to.somewhere"); ``` -------------------------------- ### Create a basic JSON index Source: https://upstash.com/docs/redis/search/index-management Demonstrates how to initialize a search index for JSON data with a defined schema. This operation should be performed once, rather than at runtime. ```TypeScript import { Redis, s } from "@upstash/redis"; const redis = Redis.fromEnv(); // Basic index on JSON data const users = await redis.search.createIndex({ name: "users", dataType: "json", prefix: "user:", schema: s.object({ name: s.string(), email: s.string(), age: s.number(), }), }); ``` ```Python from upstash_redis import Redis redis = Redis.from_env() users = redis.search.create_index( name="users", data_type="json", prefix="user:", schema={ "name": "TEXT", "email": "TEXT", "age": "U64", }, ) ``` ```Redis CLI # Basic index on hash data SEARCH.CREATE users on JSON PREFIX 1 user: SCHEMA name TEXT email TEXT age u64 ``` -------------------------------- ### GET /stream/{key} Source: https://upstash.com/docs/redis/overall/llms-txt Returns a range of entries in the stream associated with the given key. ```APIDOC ## GET /stream/{key} ### Description Returns a range of entries in the stream associated with the given key. ### Method GET ### Endpoint `/stream/{key}` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the stream. #### Query Parameters - **start** (string) - Required - The start ID of the range. Use `-` for the first entry. - **stop** (string) - Required - The stop ID of the range. Use `+` for the last entry. - **count** (integer) - Optional - The maximum number of entries to return. - **withvalues** (boolean) - Optional - If true, return the elements of the stream entries. ### Request Example ```javascript redis.xrange(key, "-", "+"); ``` ### Response #### Success Response (200) - **entries** (object) - An object where keys are entry IDs and values are the entry data. #### Response Example ```json { "1548149259438-0": { "field1": "value1", "field2": "value2" }, "1548149259438-1": { "field1": "value3", "field2": "value4" } } ``` ``` -------------------------------- ### Check Redis Key Existence with Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `exists` command with a Python Redis client. This example shows setting keys, checking their existence, deleting a key, and then re-checking existence to verify the command's behavior. ```APIDOC ## Check Redis Key Existence with Python ### Description Demonstrates how to use the `exists` command with a Python Redis client. This example shows setting keys, checking their existence, deleting a key, and then re-checking existence to verify the command's behavior. ### Method N/A (SDK Example) ### Endpoint N/A (SDK Example) ### Parameters None ### Request Example ```python redis.set("key1", "Hello") redis.set("key2", "World") assert redis.exists("key1", "key2") == 2 redis.delete("key1") assert redis.exists("key1", "key2") == 1 ``` ### Response N/A (SDK Example) ``` -------------------------------- ### Create SST + Next.js App Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new project using SST with a standard Next.js template, setting up the basic application structure. After execution, navigate into the created directory and install npm dependencies. ```APIDOC ## Create SST + Next.js App ### Description Initializes a new project using the Serverless Stack (SST) framework with a standard Next.js template, setting up the basic application structure. ### Method Command Line Interface (CLI) ### Endpoint N/A (CLI command) ### Parameters #### `create-sst` Parameters - **--template** (string) - Optional - Specifies the template to use. Defaults to 'standard/nextjs'. ### Request Example ```shell npx create-sst@latest --template standard/nextjs cd my-sst-app npm install ``` ### Response - The command output will indicate the progress and completion of project creation and dependency installation. ``` -------------------------------- ### GET /hvals Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves all values associated with fields in a hash stored at the specified key. ```APIDOC ## GET /hvals ### Description Returns all values in the hash stored at key. ### Method GET ### Endpoint /hvals ### Parameters #### Query Parameters - **key** (str) - Required - The key of the hash. ### Response #### Success Response (200) - **values** (List[str]) - Required - All values in the hash, or an empty list when key does not exist. #### Response Example ```json { "values": ["Hello", "World"] } ``` ### Request Example ```python # Assuming 'redis' is an initialized Upstash Redis client redis.hset("myhash", values={"field1": "Hello", "field2": "World"}) response = redis.hvals("myhash") print(response) # Expected output: ['Hello', 'World'] ``` ``` -------------------------------- ### Initialize Koyeb App with Upstash Redis via CLI Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Koyeb application from a GitHub repository, configuring environment variables for Upstash Redis and port mappings. ```APIDOC ## Initialize Koyeb App with Upstash Redis ### Description Initializes a new Koyeb application from a GitHub repository, configuring environment variables for Upstash Redis and port mappings. Requires replacing placeholders with actual GitHub and Upstash credentials. ### Method CLI Command ### Endpoint N/A ### Parameters #### Command Line Arguments - **app-name** (string) - Required - The name of the Koyeb app. - **--git** (string) - Required - The GitHub repository URL. - **--git-branch** (string) - Optional - The branch of the Git repository. - **--ports** (string) - Optional - Port mappings for the application. - **--routes** (string) - Optional - Routes configuration for the application. - **--env** (string) - Optional - Environment variables to set for the application. ### Request Example ```bash koyeb app init example-koyeb-upstash \ --git github.com// \ --git-branch main \ --ports 3000:http \ --routes /:3000 \ --env PORT=3000 \ --env UPSTASH_REDIS_REST_URL="" \ --env UPSTASH_REDIS_REST_TOKEN="" ``` ### Response N/A (CLI Output) ``` -------------------------------- ### Connect to Upstash Redis using ioredis (JavaScript) Source: https://upstash.com/docs/redis/overall/llms-txt Example showing how to connect to an Upstash Redis database using the `ioredis` library in Node.js and perform basic set/get operations. ```APIDOC ## Connect and Basic Operations with ioredis (JavaScript) ### Description Demonstrates how to establish a connection to Upstash Redis using the `ioredis` library in a Node.js environment and perform basic `SET` and `GET` operations. ### Method `new Redis()` and basic commands (`set`, `get`) ### Endpoint N/A (SDK Usage) ### Parameters #### Environment Variables (Recommended) - **UPSTASH_REDIS_REST_URL** (string) - Required - The URL for your Upstash Redis instance. - **UPSTASH_REDIS_REST_TOKEN** (string) - Required - The token for your Upstash Redis instance. ### Request Example ```javascript import Redis from 'ioredis'; // Use environment variables for credentials const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN, }); async function run() { await redis.set('mykey', 'myvalue'); const value = await redis.get('mykey'); console.log(value); } run(); ``` ### Response #### Success Response (200) - **set**: Returns 'OK' upon successful setting of a key-value pair. - **get**: Returns the value associated with the key, or `null` if the key does not exist. ``` -------------------------------- ### POST /edge/redis Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates setting and getting data from Upstash Redis using Cloudflare Workers for edge-based applications. ```APIDOC ## POST /edge/redis ### Description Sets and gets data from Upstash Redis using Cloudflare Workers, enabling edge data access. ### Method POST ### Endpoint /edge/redis ### Parameters #### Request Body - **key** (string) - The key to set in Redis. - **value** (string) - The value to set for the key. ### Request Example ```javascript import { Redis } from '@upstash/redis'; const redis = new Redis({ url: env.REDIS_URL, token: env.REDIS_TOKEN, }); export default { async fetch(request, env) { await redis.set('edge_data', 'hello from the edge'); const data = await redis.get('edge_data'); return new Response(data); }, }; ``` ### Response #### Success Response (200) - **data** (string) - The data retrieved from Redis. #### Response Example "hello from the edge" ``` -------------------------------- ### Run Celery Worker Source: https://upstash.com/docs/redis/overall/llms-txt Starts a Celery worker process to monitor and execute tasks. ```APIDOC ## Run Celery Worker ### Description Starts a Celery worker process. This command tells Celery to monitor the specified application ('tasks') for new tasks and execute them with informational logging. ### Command ```bash celery -A tasks worker --loglevel=info ``` ``` -------------------------------- ### Create SST + Next.js App Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new project using SST with a standard Next.js template. After execution, it instructs the user to navigate into the created directory and install npm dependencies. ```shell npx create-sst@latest --template standard/nextjs cd my-sst-app npm install ``` -------------------------------- ### HSET Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt This example demonstrates how to set a field in a Redis hash using the HSET command in TypeScript. It also shows how to set an expiration time for the field and retrieve its time-to-live (TTL). ```APIDOC ## HSET Command with Expiration (TypeScript) ### Description Sets a field in a Redis hash and optionally sets an expiration time for that field. It also demonstrates retrieving the time-to-live (TTL) for the field. ### Method Client Method Call ### Endpoint N/A (Command executed via client) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (string) - Required - The key of the hash. - **field** (string) - Required - The field within the hash. - **value** (string) - Required - The value to set for the field. - **ttl** (integer) - Optional - The time-to-live in seconds for the field. ### Request Example ```typescript // Set a field with a value and an expiration time of 10 seconds await redis.hset("my-key", "my-field", "my-value"); await redis.hexpire("my-key", "my-field", 10); // Get the time-to-live for the field const ttl = await redis.httl("my-key", "my-field"); console.log(ttl); // e.g., [9] ``` ### Response #### Success Response (200) - **ttl** (integer) - The remaining time to live of the field in seconds. Returns -1 if the field exists but has no associated expire, and -2 if the field does not exist. #### Response Example ```json 9 ``` ``` -------------------------------- ### Run Express Application (Bash) Source: https://upstash.com/docs/redis/overall/llms-txt Executes an 'index.js' file using Node.js to start an Express server, making the application accessible on the configured port. ```bash node index.js ``` -------------------------------- ### Initialize Serverless Project and Install Dependencies Source: https://upstash.com/docs/redis/overall/llms-txt Scaffolds a new Serverless Framework project, installs npm dependencies, and configures package.json. This is essential for deploying serverless applications with Upstash Redis. ```shell serverless cd counter-serverless npm install ``` ```json { "dependencies": { "@upstash/redis": "latest" } } ``` -------------------------------- ### Redis GET Command Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the value associated with a specific key from the Redis store. ```APIDOC ## GET /get ### Description Return the value of the specified key or `null` if the key doesn't exist. ### Method GET ### Parameters #### Query Parameters - **key** (string) - Required - The key to retrieve. ### Response #### Success Response (200) - **value** (string/null) - The value stored at the key or `null` if the key doesn't exist. ### Response Example { "value": "bar" } ``` -------------------------------- ### ZPOPMAX TypeScript Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to call the ZPOPMAX command using the Upstash Redis client in TypeScript, retrieving a specified number of elements. ```APIDOC ## ZPOPMAX ### Description Removes and returns the element with the highest score from a sorted set. ### Method `ZPOPMAX` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```typescript const popped = await redis.zpopmax("key", 4); ``` ### Response #### Success Response (200) - elements (Array<[member: string, score: number]>) - An array of elements popped from the sorted set. ``` -------------------------------- ### Install Upstash Redis SDK for Node.js Source: https://upstash.com/docs/redis/overall/llms-txt Installs the official Upstash Redis JavaScript SDK as a dependency for the Cloudflare Worker project. This allows the worker to interact with the Upstash Redis database. ```APIDOC ## Install Upstash Redis SDK for Node.js ### Description Installs the official Upstash Redis JavaScript SDK as a dependency for the Cloudflare Worker project. This allows the worker to interact with the Upstash Redis database. ### Method Shell command ### Endpoint N/A ### Parameters N/A ### Request Example ```shell cd greetings-cloudflare npm install @upstash/redis ``` ### Response N/A ``` -------------------------------- ### GET /functions/stats Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves statistics about the function running engines, including the number of libraries and functions for each engine. ```APIDOC ## GET /functions/stats ### Description Retrieves statistics about the function running engines, including the number of libraries and functions for each engine. ### Method GET ### Endpoint /functions/stats ### Parameters #### Query Parameters - None ### Request Body - None ### Response #### Success Response (200) - **engines** (Object) - Stats about the engines and functions. #### Response Example { "engines": { "LUA": { "librariesCount": 3, "functionsCount": 15 } } } ``` -------------------------------- ### Initialize Upstash Redis client in Deno Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to initialize an Upstash Redis client in Deno environments, supporting both explicit configuration and environment variable loading. ```typescript import { Redis } from "https://deno.land/x/upstash_redis/mod.ts" // Explicit Configuration const redis = new Redis({ url: "", token: "", }) // From Environment Variables const redisFromEnv = Redis.fromEnv(); ``` -------------------------------- ### ZREM Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZREM command to remove members from a sorted set using the Upstash Redis client. ```APIDOC ## ZREM Command Example ### Description Demonstrates how to use the ZREM command in Python with the Upstash Redis client. It shows adding initial members to a sorted set and then removing specific members. ### Method POST ### Endpoint /redis/v1/command ### Request Body - **command** (string) - Required - ZREM - **key** (string) - Required - The sorted set key - **members** (array) - Required - The members to remove ### Request Example { "command": "ZREM", "key": "mysortedset", "members": ["member1", "member2"] } ### Response #### Success Response (200) - **result** (number) - The number of members removed from the sorted set #### Response Example { "result": 2 } ``` -------------------------------- ### Get Latency Histogram API Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the latency histogram for a specified test name via a GET request to the API endpoint. This allows for analysis of performance metrics. ```APIDOC ## Get Latency Histogram API ### Description Retrieves the latency histogram for a specified test name via a GET request to the API endpoint. This allows for analysis of performance metrics. ### Method GET ### Endpoint https://v7xx4aa2ib.execute-api.us-east-1.amazonaws.com/get ### Parameters #### Path Parameters N/A #### Query Parameters - **name** (string) - Required - The name of the test for which to retrieve the histogram. ### Request Example ```shell curl https://v7xx4aa2ib.execute-api.us-east-1.amazonaws.com/get?name=perf-test-1 ``` ### Response #### Success Response (200) - **Histogram Data** (object) - The latency histogram data for the specified test name. #### Response Example ```json { "testName": "perf-test-1", "histogram": [ {"bucket": "0-1ms", "count": 100}, {"bucket": "1-5ms", "count": 50}, {"bucket": "5-10ms", "count": 10} ] } ``` ``` -------------------------------- ### Python EVAL Command Example (Upstash Redis) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates evaluating a Lua script in Python to retrieve a key's value from Upstash Redis. ```APIDOC ```python script = """ local value = redis.call("GET", KEYS[1]) return value """ redis.set("mykey", "Hello") assert redis.eval(script, keys=["mykey"]) == "Hello" ``` ``` -------------------------------- ### Publish Fastly Compute service and configure backend (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt This snippet shows the command-line interaction for publishing a Fastly Compute service and configuring a backend for Upstash Redis. It involves using the Fastly CLI to create a new service, define a domain, and set up the Redis hostname and port. The output demonstrates the success messages and prompts for configuration. ```shell > fastly compute publish ✓ Initializing... ✓ Verifying package manifest... ✓ Verifying local javascript toolchain... ✓ Building package using javascript toolchain... ✓ Creating package archive... SUCCESS: Built package 'fastly-upstash' (pkg/fastly-upstash.tar.gz) There is no Fastly service associated with this package. To connect to an existing service add the Service ID to the fastly.toml file, otherwise follow the prompts to create a service now. Press ^C at any time to quit. Create new service: [y/N] y ✓ Initializing... ✓ Creating service... Domain: [supposedly-included-corgi.edgecompute.app] Backend (hostname or IP address, or leave blank to stop adding backends): global-concise-scorpion-30984.upstash.io Backend port number: [80] 443 Backend name: [backend_1] upstash Backend (hostname or IP address, or leave blank to stop adding backends): ✓ Creating domain 'supposedly-smart-corgi.edgecompute.app'... ✓ Creating backend 'upstash' (host: global-concise-scorpion-30984.upstash.io, port: 443)... ✓ Uploading package... ✓ Activating version... ``` -------------------------------- ### Redis GET Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt This section outlines the API specification for the Redis GET command. It details the required parameters and the structure of the expected response when querying a key in Redis. ```APIDOC ## Redis GET Command API Reference ### Description This section outlines the API specification for the Redis GET command. It details the required parameters and the structure of the expected response when querying a key in Redis. ### GET Command - **Description**: Return the value of the specified key or `null` if the key doesn't exist. - **Arguments**: - **key** (string): Required - The key to get. - **Response**: - **Description**: The value stored at the key or `null` if the key doesn't exist. - **Required**: true ``` -------------------------------- ### GET /GETRANGE Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves a substring of the value stored at the specified key using start and end indices. ```APIDOC ## GET /GETRANGE ### Description Returns the substring of the string value stored at the specified key, determined by the start and end offsets. ### Method GET ### Endpoint /GETRANGE ### Parameters #### Query Parameters - **key** (string) - Required - The key associated with the string value. - **start** (integer) - Required - The starting index of the substring. - **end** (integer) - Required - The ending index of the substring. ### Request Example ```ts const substring = await redis.getrange("key", 2, 4); ``` ### Response #### Success Response (200) - **value** (string) - The requested substring. ``` -------------------------------- ### Next.js Survey App Component Source: https://upstash.com/docs/redis/overall/llms-txt Example of a UI component for a Next.js survey application integrated with Upstash Redis. ```jsx Building a Survey App with Upstash Redis and Next.js ``` -------------------------------- ### Environment Configuration Source: https://upstash.com/docs/redis/overall/llms-txt Instructions for setting up Upstash Redis environment variables using the SST CLI. ```APIDOC ## Configure Upstash Redis Environment Variables ### Description This guide details how to set Upstash Redis REST URL and Token as secure secrets using the SST CLI, ensuring they are securely available to your application at runtime. ### Commands ```shell npx sst secrets set UPSTASH_REDIS_REST_URL npx sst secrets set UPSTASH_REDIS_REST_TOKEN ``` ``` -------------------------------- ### Example Redis Commands for Pipelining Source: https://upstash.com/docs/redis/overall/llms-txt A set of standard Redis commands formatted for submission via the Upstash pipelining API. Pipelining allows for sending multiple commands at once to reduce latency. ```APIDOC ## Example Redis Commands for Pipelining ### Description A set of standard Redis commands (`SET`, `SETEX`, `INCR`, `ZADD`) formatted for submission via the Upstash pipelining API. Pipelining allows for sending multiple commands at once to reduce latency. ### Method Redis Commands ### Endpoint N/A (Pipelining API) ### Parameters N/A ### Request Example ```redis SET key1 valuex SETEX key2 13 valuez INCR key1 ZADD myset 11 item1 22 item2 ``` ### Response #### Success Response - **results** (array) - An array containing the results of each command in the pipeline. #### Response Example ```json ["OK", "OK", "2", "2"] ``` ``` -------------------------------- ### Initialize Upstash Redis Client Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to instantiate the Redis client using explicit credentials and perform a basic GET operation. This is useful for environments where environment variables are managed manually. ```TypeScript 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); } })(); ``` -------------------------------- ### Deploy Cloudflare Worker via CLI Source: https://upstash.com/docs/redis/overall/llms-txt Standard workflow for deploying a Cloudflare Worker project. Includes dependency installation and deployment execution. ```bash cd worker pnpm install npm run deploy ``` -------------------------------- ### Initialize Serverless Framework Project Source: https://upstash.com/docs/redis/overall/llms-txt Interactive CLI commands to initiate a new AWS Node.js project using the Serverless Framework. ```shell 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. ``` -------------------------------- ### GET /stream/xpending Source: https://upstash.com/docs/redis/overall/llms-txt Returns information about pending messages in a stream consumer group. It can be used to get a summary or detailed pending message information based on provided range arguments. ```APIDOC ## GET /stream/xpending ### Description Returns information about pending messages in a stream consumer group. It can be used to get a summary or detailed pending message information based on provided range arguments. ### Method GET ### Endpoint /stream/xpending ### Parameters #### Path Parameters - **key** (str) - Required - The key of the stream. - **group** (str) - Required - The consumer group name. #### Query Parameters - **start** (str) - Optional - The minimum pending ID to return. - **end** (str) - Optional - The maximum pending ID to return. - **count** (int) - Optional - The maximum number of pending messages to return. - **consumer** (str) - Optional - Filter results by a specific consumer. - **idle** (int) - Optional - Filter by minimum idle time in milliseconds. ### Request Example redis.xpending("mystream", "mygroup", start="-", end="+", count=10) ### Response #### Success Response (200) - **Any** (type) - Returns a summary or detailed pending message information. #### Response Example [ 2, "1638360173533-0", "1638360173533-1", [["consumer1", "2"]] ] ``` -------------------------------- ### Dockerfile Configuration for Node.js Source: https://upstash.com/docs/redis/overall/llms-txt A basic Dockerfile setup for a Node.js application, using a slim base image and preparing the working directory. ```dockerfile FROM node:12-slim WORKDIR /usr/src/app ``` -------------------------------- ### BITCOUNT Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the BITCOUNT command in Upstash Redis to count the number of set bits in a binary string. This example shows the basic usage without specifying a range. ```APIDOC ## BITCOUNT Command Example ### Description Counts the number of set bits in a binary string associated with a key. ### Method N/A (Redis Command) ### Endpoint N/A (Redis Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' is an initialized Upstash Redis client const key = "my-key"; const bits = await redis.bitcount(key); console.log(bits); ``` ### Response #### Success Response (200) - **bits** (number) - The number of set bits in the binary string. #### Response Example ```json 5 ``` ``` -------------------------------- ### Create Next.js App and Initialize SST Source: https://upstash.com/docs/redis/overall/llms-txt Commands to set up a new Next.js project and initialize the Serverless Stack (SST) framework for AWS deployment. ```shell npx create-next-app@latest cd my-app sst init ``` -------------------------------- ### GET /keys Source: https://upstash.com/docs/redis/overall/llms-txt Fetches all keys matching a glob-style pattern. This command is useful for discovery but should be used with caution on large datasets. ```APIDOC ## GET /keys ### Description Fetches all keys matching a glob-style pattern. Use `*` to match all keys. This command can block the database for an extended period, especially with large datasets, and will return an error for databases containing more than 100,000 entries. Consider using SCAN for production environments. ### Method GET ### Endpoint /keys ### Parameters #### Query Parameters - **match** (str) - Required - A glob-style pattern. Use `*` to match all keys. ### Request Example ```py redis.keys("prefix*") redis.keys("*") ``` ### Response #### Success Response (200) - **keys** (list) - A list of keys matching the provided pattern. #### Response Example ["user:1", "user:2", "session:abc"] ``` -------------------------------- ### Upstash Redis LPUSHX Python Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the usage of the LPUSHX command in Python with Upstash Redis. It shows how to push elements to an existing list and its behavior when the list does not exist. Assumes a Redis client instance is available. ```python 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 ``` -------------------------------- ### ACL RESTTOKEN Command Error Example Source: https://upstash.com/docs/redis/overall/llms-txt Shows an example of an error response from the `ACL RESTTOKEN` command in redis-cli when authentication fails due to an incorrect password or a non-existent user. ```APIDOC ## ACL RESTTOKEN Command Error Example ### Description Demonstrates an error scenario when using the `ACL RESTTOKEN` command with invalid credentials. ### Command ```shell redis-cli> ACL RESTTOKEN upstash fakepass ``` ### Expected Error Response ``` (error) ERR Wrong password or user "upstash" does not exist ``` ### Cause This error typically occurs if the provided username (`upstash`) does not exist or the password (`fakepass`) is incorrect. ``` -------------------------------- ### Create and navigate to demo application directory (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Shell commands to create a new directory for a demo application and then change the current working directory into the newly created directory. ```APIDOC ## Create and navigate to demo application directory (Shell) ### Description Shell commands to create a new directory for a demo application and then change the current working directory into the newly created directory. ### Method Shell Commands ### Endpoint N/A ### Parameters None ### Request Example ```bash mkdir example-koyeb-upstash cd example-koyeb-upstash ``` ### Response #### Success Response (200) - **Output**: A new directory named `example-koyeb-upstash` is created, and the current working directory is changed to it. ``` -------------------------------- ### Flush Database using Python FLUSHDB Command Source: https://upstash.com/docs/redis/overall/llms-txt Provides examples of executing the FLUSHDB command in Python, demonstrating both synchronous and asynchronous modes for clearing all keys from the selected database. Note: The example uses `flushall()` which clears all databases. ```APIDOC ## Flush Database using Python ### Description Executes the FLUSHDB command in Python, demonstrating both synchronous and asynchronous modes for clearing all keys from the selected database. Note: The example uses `flushall()` which clears all databases. ### Method POST (Implicit for SDK calls) ### Endpoint (Not applicable for SDK method) ### Parameters (Not applicable for SDK method) ### Request Example ```python redis.flushall() ``` ### Response (Not applicable for SDK method) ### Request Example 2 ```python redis.flushall(flush_type="ASYNC") ``` ``` -------------------------------- ### Initialize Node.js Project Dependencies Source: https://upstash.com/docs/redis/overall/llms-txt Commands to initialize a Node.js project and install essential packages for web applications, including Express and Redis integration libraries. ```bash npm init npm install express redis connect-redis express-session ``` -------------------------------- ### Configure Google Cloud Project and Enable Services (Bash) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to configure the Google Cloud SDK using Bash commands. It sets the active project and enables the Cloud Run API and Cloud Build API, which are necessary for deploying applications to Google Cloud Run. ```bash gcloud config set project cloud-run-sessions gcloud services enable run.googleapis.com gcloud services enable cloudbuild.googleapis.com ``` -------------------------------- ### Dockerfile for Node.js Application Source: https://upstash.com/docs/redis/overall/llms-txt Defines the steps to build a container image for a Node.js application using Docker. It includes copying project files, installing npm dependencies, and setting the start command. ```dockerfile COPY package*.json ./ RUN npm install COPY . ./ CMD [ "npm", "start" ] ``` -------------------------------- ### Upstash REST API URL Mapping Source: https://upstash.com/docs/redis/overall/llms-txt Provides examples demonstrating how various Redis commands are translated into corresponding URL paths for the Upstash REST API. ```APIDOC ## Upstash REST API URL Mapping for Redis Commands ### Description This section illustrates how common Redis commands map to URL paths when using the Upstash REST API. This is useful for direct HTTP requests to your Redis instance. ### Method GET/POST (REST) ### Endpoint `REST_URL/[command]/[args...]` ### Request Example - `SET foo bar` -> `REST_URL/set/foo/bar` - `SET foo bar EX 100` -> `REST_URL/set/foo/bar/EX/100` - `GET foo` -> `REST_URL/get/foo` - `MGET foo1 foo2 foo3` -> `REST_URL/mget/foo1/foo2/foo3` - `HGET employee:23381 salary` -> `REST_URL/hget/employee:23381/salary` - `ZADD teams 100 team-x 90 team-y` -> `REST_URL/zadd/teams/100/team-x/90/team-y` ``` -------------------------------- ### Manage Redis Hashes in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates populating a hash with HSET and retrieving all fields with HGETALL. ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hgetall("myhash") == {"field1": "Hello", "field2": "World"} ``` -------------------------------- ### Add Data to Redis Index Source: https://upstash.com/docs/redis/search/getting-started This snippet demonstrates how to add JSON data to a Redis index. It uses standard Redis JSON commands to set key-value pairs, ensuring keys match the index prefix for automatic indexing. The Python example includes a call to wait for indexing to complete. ```TypeScript await redis.json.set("product:1", "$", { name: "Wireless Headphones", description: "Premium noise-cancelling wireless headphones with 30-hour battery life", category: "electronics", price: 199.99, inStock: true, }); await redis.json.set("product:2", "$", { name: "Running Shoes", description: "Lightweight running shoes with advanced cushioning technology", category: "sports", price: 129.99, inStock: true, }); ``` ```Python redis.json().set("product:1", "$", { "name": "Wireless Headphones", "description": "Premium noise-cancelling wireless headphones with 30-hour battery life", "category": "electronics", "price": 199.99, "inStock": True, }) redis.json().set("product:2", "$", { "name": "Running Shoes", "description": "Lightweight running shoes with advanced cushioning technology", "category": "sports", "price": 129.99, "inStock": True, }) index.wait_indexing() ``` ```Redis CLI JSON.SET product:1 $ '{"name": "Wireless Headphones", "description": "Premium noise-cancelling wireless headphones with 30-hour battery life", "category": "electronics", "price": 199.99, "inStock": true}' JSON.SET product:2 $ '{"name": "Running Shoes", "description": "Lightweight running shoes with advanced cushioning technology", "category": "sports", "price": 129.99, "inStock": true}' SEARCH.WAITINDEXING products ``` -------------------------------- ### MSET Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt This Python snippet demonstrates how to use the `MSET` command with the Upstash Redis client to efficiently set multiple key-value pairs in a single operation. ```APIDOC ## MSET Command Example (Python) ### Description This Python snippet demonstrates how to use the `MSET` command with the Upstash Redis client to efficiently set multiple key-value pairs in a single operation. ### Method SDK Method (Python) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **key-value pairs** (dict) - Required - A dictionary where keys are the Redis keys and values are the corresponding values to set. ### Request Example ```python redis.mset({ "key1": "value1", "key2": "value2" }) ``` ### Response #### Success Response (200) - **Status** (boolean) - Indicates if the operation was successful. #### Response Example ```json True ``` ``` -------------------------------- ### Initialize Serverless Framework Project Source: https://upstash.com/docs/redis/overall/llms-txt Scaffolds a new Serverless Framework project using the AWS Node.js HTTP API template. ```shell serverless cd ratelimit-serverless ``` -------------------------------- ### UNLINK Command Example in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the UNLINK command with the Upstash Redis client in Python, asserting the number of keys unlinked. ```APIDOC ## UNLINK Command Example in Python ### Description Removes one or more keys from the Redis store. ### Method ``` redis.unlink(key1, key2, ...) ``` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python assert redis.unlink("key1", "key2", "key3") == 3 ``` ### Response #### Success Response (200) An integer representing the number of keys unlinked. #### Response Example ```json 3 ``` ``` -------------------------------- ### Run Python Script Source: https://upstash.com/docs/redis/overall/llms-txt Provides the command-line instruction to execute the main Python script. ```APIDOC ## Run Python Script ### Description Provides the command-line instruction to execute the main Python script. ### Command ```bash python your_script_name.py ``` ``` -------------------------------- ### Serverless Redis Handler (JavaScript) Source: https://upstash.com/docs/redis/overall/llms-txt Example of a serverless function handler for Redis operations in JavaScript, including client initialization and connection closing. ```APIDOC ## Serverless Redis Handler (JavaScript) ### Description Example of a serverless function handler for Redis operations in JavaScript, including client initialization and connection closing. ### Method exports.handler ### Parameters #### Environment Variables - **REDIS_URL** (string) - Required - The URL for the Redis connection. ### Example ```javascript 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" }; }; ``` ``` -------------------------------- ### TypeScript SCRIPT EXISTS Example Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating how to use the `scriptExists` method with the Upstash Redis client in TypeScript. It takes one or more SHA1 hashes as input and returns an array indicating the existence of each script. ```APIDOC ## SCRIPT EXISTS Example (TypeScript) ### Description Checks if one or more Lua scripts, identified by their SHA1 hashes, exist in the Redis cache. ### Method `scriptExists` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```typescript await redis.scriptExists("", "") ``` ### Response #### Success Response (200) - **result** (Array) - An array where each element is `1` if the corresponding script exists, and `0` otherwise. #### Response Example ``` // For input: await redis.scriptExists("", "") // Returns: [1, 0] ``` ``` -------------------------------- ### Run Redis Commands (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Provides examples of executing Redis commands using both synchronous and asynchronous Upstash Redis clients. ```python from upstash_redis import Redis redis = Redis.from_env() def main(): redis.set("a", "b") print(redis.get("a")) # or for async context: from upstash_redis.asyncio import Redis redis = Redis.from_env() async def main(): await redis.set("a", "b") print(await redis.get("a")) ``` -------------------------------- ### GET /lrange Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves a range of elements from a list stored at a specified key, supporting negative offsets. ```APIDOC ## GET /lrange ### Description Returns the specified elements of the list stored at key. ### Method GET ### Endpoint /lrange ### Parameters #### Query Parameters - **key** (str) - Required - The key of the list. - **start** (int) - Required - The starting index of the range to return. Use negative numbers to specify offsets starting at the end of the list. - **end** (int) - Required - The ending index of the range to return. Use negative numbers to specify offsets starting at the end of the list. ### Response #### Success Response (200) - **List[str]** - The list of elements in the specified range. #### Response Example { "example": [ "one", "two" ] } ### Request Example ```py redis.rpush("mylist", "one", "two", "three") assert redis.lrange("mylist", 0, 1) == ["one", "two"] assert redis.lrange("mylist", 0, -1) == ["one", "two", "three"] ``` ``` -------------------------------- ### Initialize and Configure Serverless Project Source: https://upstash.com/docs/redis/tutorials/using_serverless_framework Commands to scaffold a new Serverless Framework project, install necessary dependencies, and define the package configuration. ```shell serverless cd counter-serverless npm install ``` ```json { "dependencies": { "@upstash/redis": "latest" } } ``` -------------------------------- ### Redis ZINTERSTORE Command Source: https://upstash.com/docs/redis/overall/llms-txt This entry represents the ZINTERSTORE command in Redis. No specific code example or detailed description was provided in the source. ```APIDOC ## Redis ZINTERSTORE Command ### Description Represents the ZINTERSTORE command in Redis. No specific code example or detailed description was provided in the source. ### Method (Not specified) ### Endpoint (Not specified) ### Parameters (Not specified) ### Request Example ```Redis ZINTERSTORE ``` ### Response (Not specified) ``` -------------------------------- ### GET /stream/{key} Source: https://upstash.com/docs/redis/overall/llms-txt Fetches stream entries from a Redis stream that match a given range of IDs. ```APIDOC ## GET /stream/{key} ### Description Returns stream entries matching a given range of IDs. ### Method GET ### Endpoint /stream/{key} ### Parameters #### Path Parameters - **key** (str) - Required - The key of the stream. #### Query Parameters - **start** (str) - Optional - The stream entry ID to start from. Use "-" for the first available ID. Defaults to "-". - **end** (str) - Optional - The stream entry ID to end at. Use "+" for the last available ID. Defaults to "+". - **count** (int) - Optional - The maximum number of entries to return. ### Response #### Success Response (200) - **Response** (List[Tuple[str, List[str]]]) - A list of stream entries, where each entry is a tuple containing the stream ID and its associated fields and values. #### Response Example ```json { "1548149259438-0": { "field1": "value1", "field2": "value2" }, "1548149259438-1": { "field1": "value3", "field2": "value4" } } ``` ``` -------------------------------- ### Initialize Git Repository and Push to GitHub Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a Git repository, adds files, creates a commit, sets a remote origin to GitHub, and pushes the main branch. This is a standard workflow for version control and deployment. ```bash git init echo 'node_modules' >> .gitignore git add . git commit -m "Initial commit" git remote add origin git@github.com:/.git git push -u origin main ``` -------------------------------- ### REST API: SET Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Provides an example of sending a Redis SET command as a JSON array in the body of an HTTP POST request to the Upstash REST API. Includes setting a key-value pair with an expiration. ```APIDOC ## REST API: SET Command Example ### Description Sends a Redis SET command as a JSON array in the body of an HTTP POST request to the Upstash REST API. Includes setting a key-value pair with an expiration. ### Method POST ### Endpoint `https://` ### Parameters #### Request Body - **command** (array): Required - The Redis command and its arguments, e.g., `["SET", "key", "value", "EX", 100] ### Request Example ```shell curl -X POST -d '["SET", "foo", "bar", "EX", 100]' https://us1-merry-cat-32748.upstash.io \ -H "Authorization: Bearer " ``` ### Response #### Success Response (200) - **result** (string) - The result of the command (e.g., 'OK'). #### Response Example ```json { "result": "OK" } ``` ``` -------------------------------- ### Install Dependencies for FastAPI and Rate Limiting Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary Python packages including FastAPI, the Upstash Redis client, the rate limiting library, and the Uvicorn ASGI server. ```shell pip install fastapi upstash-redis upstash-ratelimit uvicorn[standard] ``` -------------------------------- ### Initialize Django Project Source: https://upstash.com/docs/redis/overall/llms-txt Standard commands to scaffold a new Django project and a specific application module. ```shell django-admin startproject myproject cd myproject python manage.py startapp myapp ``` -------------------------------- ### REST API: SET Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Provides an example of sending a Redis SET command as a JSON array in the body of an HTTP POST request to the Upstash REST API. Includes setting a key-value pair with an expiration. ```shell curl -X POST -d '["SET", "foo", "bar", "EX", 100]' https://us1-merry-cat-32748.upstash.io \ -H "Authorization: Bearer 2553feg6a2d9842h2a0gcdb5f8efe9934" ``` -------------------------------- ### Execute Scripts and Applications via Bash Source: https://upstash.com/docs/redis/overall/llms-txt Provides standard shell commands to execute Python scripts or start a Flask development server. These commands assume the environment is properly configured with necessary dependencies. ```bash python your_script_name.py ``` ```bash python app.py ``` -------------------------------- ### Python HSET, HPEXPIRE, HPERSIST Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the usage of `redis.hset`, `redis.hpexpire`, and `redis.hpersist` functions in Python, asserting the expected outcome of removing expiration. ```APIDOC ```python redis.hset(hash_name, field, value) redis.hpexpire(hash_name, field, 1000) assert redis.hpersist(hash_name, field) == [1] ``` ``` -------------------------------- ### Initialize Git Repository and Push to GitHub Source: https://upstash.com/docs/redis/quickstarts/koyeb This sequence of bash commands initializes a Git repository, adds all project files to be tracked, creates an initial commit, sets up a remote origin to a GitHub repository, and pushes the main branch. This is a standard workflow for version control and deployment. ```bash git init echo 'node_modules' >> .gitignore git add . git commit -m "Initial commit" git remote add origin git@github.com:/.git git push -u origin main ``` -------------------------------- ### JSON.SET Python Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the basic usage of the `redis.json.set` method to set a JSON value at a specified path within a given key. ```APIDOC ## JSON.SET ### Description Sets a JSON value at a specified path within a key. ### Method `JSON.SET` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```python redis.json.set(key, "$.path", value) ``` ### Response #### Success Response (200) - status (string) - OK #### Response Example ```json "OK" ``` ``` -------------------------------- ### ACL RESTTOKEN Command Error Example (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Shows an example of an error response from the `ACL RESTTOKEN` command in redis-cli when authentication fails due to an incorrect password or a non-existent user. ```shell redis-cli> ACL RESTTOKEN upstash fakepass (error) ERR Wrong password or user "upstash" does not exist ``` -------------------------------- ### Create and Navigate Laravel Project Source: https://upstash.com/docs/redis/overall/llms-txt Commands to scaffold a new Laravel application and enter the project directory. ```shell laravel new todo-cache cd todo-cache ``` -------------------------------- ### Install Laravel API Package Source: https://upstash.com/docs/redis/overall/llms-txt Artisan command to install the API scaffolding for a Laravel application. ```shell php artisan install:api ``` -------------------------------- ### Deploy Application to Koyeb Source: https://upstash.com/docs/redis/overall/llms-txt Deploys an application to Koyeb using the CLI, configuring necessary settings for Upstash Redis integration. ```APIDOC ## Deploy Application to Koyeb ### Description Deploys an application to Koyeb using the CLI, configuring necessary settings for Upstash Redis integration. ### Method CLI Command ### Endpoint N/A (CLI Command) ### Parameters #### CLI Arguments - **`example-koyeb-upstash`** (string) - The name of the Koyeb application. - **`--git`** (string) - The Git repository URL (e.g., `github.com//`). - **`--git-branch`** (string) - The Git branch to deploy (e.g., `main`). - **`--ports`** (string) - Defines the ports to expose (e.g., `3000:http`). - **`--routes`** (string) - Defines the routing rules (e.g., `/:3000`). - **`--env`** (string) - Environment variables to set (e.g., `PORT=3000`, `UPSTASH_REDIS_REST_URL=...`, `UPSTASH_REDIS_REST_TOKEN=...`). ### Request Example ```bash koyeb app init example-koyeb-upstash \ --git github.com// \ --git-branch main \ --ports 3000:http \ --routes /:3000 \ --env PORT=3000 \ --env UPSTASH_REDIS_REST_URL="" \ --env UPSTASH_REDIS_REST_TOKEN="" ``` ### Response #### Success Response - Output from the Koyeb CLI indicating successful deployment. ``` -------------------------------- ### Manage Dynamic Rate Limiting in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates setting and retrieving dynamic rate limits using the Upstash Ratelimit SDK. ```typescript ratelimit.getDynamicLimit(): Promise<{ dynamicLimit: number | null }> const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10s"), dynamicLimits: true, }); await ratelimit.setDynamicLimit({ limit: 5 }); const { dynamicLimit } = await ratelimit.getDynamicLimit(); // returns 5 ``` -------------------------------- ### Create Next.js App and Initialize SST Source: https://upstash.com/docs/redis/overall/llms-txt These commands set up a new Next.js project and initialize the Serverless Stack (SST) framework within it. SST simplifies the deployment and management of serverless applications on AWS. ```APIDOC ## Create Next.js App and Initialize SST ### Description These commands set up a new Next.js project and initialize the Serverless Stack (SST) framework within it. SST simplifies the deployment and management of serverless applications on AWS. ### Method Shell Commands ### Endpoint N/A ### Parameters None ### Request Example ```bash npx create-next-app@latest cd my-app sst init ``` ### Response #### Success Response (200) - **Output**: New Next.js project created and SST initialized within the `my-app` directory. ``` -------------------------------- ### Execute Basic Redis Commands via REST API Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to execute fundamental Redis commands like GET, SET, MGET, and HGET using HTTP requests with a Bearer token for authentication. ```bash # GET command example curl https://us1-merry-cat-32748.upstash.io/get/foo \ -H "Authorization: Bearer " # POST SET command example curl https://us1-merry-cat-32748.upstash.io/set/foo/bar \ -H "Authorization: Bearer " # POST SET with expiration example curl https://us1-merry-cat-32748.upstash.io/set/key/value/EX/100 \ -H "Authorization: Bearer " # GET MGET command example curl https://us1-merry-cat-32748.upstash.io/mget/key1/key2/key3 \ -H "Authorization: Bearer " # GET HGET command example curl https://us1-merry-cat-32748.upstash.io/hget/employee:23381/salary \ -H "Authorization: Bearer " ``` -------------------------------- ### LPUSHX Command Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/list/lpushx Demonstrates the usage of the LPUSHX command in Python. It shows how to initialize a list, push multiple elements to an existing list, and handle cases where the list does not exist. This command is useful for conditionally adding elements to the beginning of a list. ```python import redis # Assuming 'redis' is an initialized Redis client instance # Initialize the list redis.lpush("mylist", "one") # Push multiple elements to an existing list assert redis.lpushx("mylist", "two", "three") == 3 # Verify the list content # Note: The lrange function is assumed to be defined elsewhere or is a placeholder for a Redis client method # assert lrange("mylist", 0, -1) == ["three", "two", "one"] # Attempt to push to a non-existent list assert redis.lpushx("non-existent-list", "one") == 0 ``` -------------------------------- ### Test API Endpoints with cURL Source: https://upstash.com/docs/redis/overall/llms-txt Provides example cURL commands to interact with a Todo API, demonstrating GET, POST, PUT, and DELETE operations. These commands are useful for testing API integrations. ```shell curl http://todo-cache.test/api/todos curl http://todo-cache.test/api/todos/1 curl -X POST http://todo-cache.test/api/todos -H "Content-Type: application/json" -d '{"title":"New Todo"}' curl -X PUT http://todo-cache.test/api/todos/1 -H "Content-Type: application/json" -d '{"title":"Updated Todo"}' curl -X DELETE http://todo-cache.test/api/todos/1 ``` -------------------------------- ### Install BullMQ and Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Installs necessary dependencies for integrating BullMQ with Upstash Redis. ```bash npm install bullmq upstash-redis ``` -------------------------------- ### Example Lambda Test Event Source: https://upstash.com/docs/redis/howto/getstartedawslambda A sample JSON payload used to test the AWS Lambda function input. ```json { "key": "foo", "value": "bar" } ``` -------------------------------- ### Run Redis Commands (Python) Source: https://upstash.com/docs/redis/sdks/py/gettingstarted Provides examples of executing Redis commands using both synchronous and asynchronous Upstash Redis clients. Demonstrates setting and getting a key. ```python from upstash_redis import Redis redis = Redis.from_env() def main(): redis.set("a", "b") print(redis.get("a")) # or for async context: from upstash_redis.asyncio import Redis redis = Redis.from_env() async def main(): await redis.set("a", "b") print(await redis.get("a")) ``` -------------------------------- ### Get Random Key Source: https://upstash.com/docs/redis/overall/llms-txt Returns a single random key from the current database. Returns null if the database is empty. ```json {} ``` -------------------------------- ### Install Dependencies for FastAPI and Redis (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Installs necessary Python packages including FastAPI, the Upstash Redis client, and the Uvicorn ASGI server. ```shell pip install fastapi upstash-redis uvicorn[standard] ``` -------------------------------- ### Initialize Serverless Stack (SST) Source: https://upstash.com/docs/redis/overall/llms-txt Command to initialize the Serverless Stack (SST) framework within a project directory for serverless deployments. ```bash sst init ``` -------------------------------- ### Create Next.js App and Initialize SST Source: https://upstash.com/docs/redis/overall/llms-txt Commands to create a new Next.js application and initialize the Serverless Stack (SST) framework within the project. SST simplifies the deployment of serverless applications on AWS. ```APIDOC ## Create Next.js App and Initialize SST ### Description Commands to create a new Next.js application and initialize the Serverless Stack (SST) framework within the project. SST simplifies the deployment of serverless applications on AWS. ### Command ```shell npx create-next-app@latest cd my-app sst init ``` ``` -------------------------------- ### Create a basic search index Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to initialize a search index with a specific prefix and schema. Supports string data types and allows skipping initial scans of existing keys. ```APIDOC ## Create a basic search index ### Description Initializes a search index with a specified name, data type, prefix, and schema. Optionally skips an initial scan of existing keys. ### Method Client-side command execution ### Endpoint N/A (Client-side operation) ### Parameters #### `createIndex` Parameters (TypeScript) - **name** (string) - Required - The name of the search index. - **dataType** (string) - Required - The data type of the index (e.g., 'string'). - **prefix** (string) - Required - The prefix for keys to be indexed. - **skipInitialScan** (boolean) - Optional - If true, skips scanning existing keys during index creation. - **schema** (object) - Required - The schema definition for the index. #### `create_index` Parameters (Python) - **name** (string) - Required - The name of the search index. - **data_type** (string) - Required - The data type of the index (e.g., 'string'). - **prefixes** (string) - Required - The prefix for keys to be indexed. - **skip_initial_scan** (boolean) - Optional - If true, skips scanning existing keys during index creation. - **schema** (dict) - Required - The schema definition for the index. #### `SEARCH.CREATE` Parameters (Redis CLI) - **ON** (string) - Required - Specifies the index type (e.g., 'STRING'). - **** (string) - Required - The name of the search index. - **PREFIX** (integer) - Required - The number of prefixes. - **** (string) - Required - The prefix for keys to be indexed. - **SKIPINITIALSCAN** - Optional - Flag to skip initial scan. - **SCHEMA** - Required - Defines the schema fields. ### Request Example (TypeScript) ```typescript const profiles = await redis.search.createIndex({ name: "profiles", dataType: "string", prefix: "profiles:", skipInitialScan: true, schema: s.object({ name: s.string(), }), }); ``` ### Request Example (Python) ```python profiles = redis.search.create_index( name="profiles", data_type="string", prefixes="profiles:", skip_initial_scan=True, schema={ "name": "TEXT", }, ) ``` ### Request Example (Redis CLI) ```bash SEARCH.CREATE profiles ON STRING PREFIX 1 profiles: SKIPINITIALSCAN SCHEMA name TEXT ``` ### Response #### Success Response - **status** (string) - Indicates the success of the index creation (e.g., 'OK'). ``` -------------------------------- ### GET /null-result Source: https://upstash.com/docs/redis/overall/llms-txt Represents the standard JSON response format from the Upstash REST API when a query returns no data. ```APIDOC ## JSON Response for Null Result ### Description Example of a JSON response from the Upstash REST API when a Redis command returns a `null` value. ### Response Example { "result": null } ``` -------------------------------- ### Initialize Upstash Redis in Node.js/Browser Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates initializing the Upstash Redis client in Node.js or browser environments using URL and token or environment variables. ```APIDOC ## Initialize Upstash Redis in Node.js/Browser ### Description Demonstrates initializing the Upstash Redis client in Node.js or browser environments. It shows how to configure the client using explicit URL and token, or by loading directly from environment variables using `Redis.fromEnv()`, which is suitable for serverless platforms. ### Method Class Instantiation ### Parameters #### Initialization Options - **url** (string) - Required - The Upstash Redis REST URL. - **token** (string) - Required - The Upstash Redis REST token. ### Request Example (TypeScript) ```typescript import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // or load directly from env const redis = Redis.fromEnv() ``` ``` -------------------------------- ### Initialize AWS CDK Project and Dependencies (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Commands to create a new CDK directory, initialize a TypeScript project, and install the Upstash Redis SDK. ```shell mkdir counter-cdk && cd counter-cdk cdk init app --language typescript npm install @upstash/redis ``` -------------------------------- ### Install @upstash/search-ioredis and ioredis Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary packages for using Redis Search with ioredis. This includes the adapter package and the ioredis client itself. ```bash npm install @upstash/search-ioredis ioredis ``` -------------------------------- ### SMOVE Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the SMOVE command in Python. It shows adding members to source and destination sets, moving a member from source to destination, and verifying the sets' contents using a Redis client. This client-side command execution requires an initialized Redis client instance. ```python # Assuming 'redis' is an initialized Redis client instance # Add members to source and destination sets (example) redis.sadd('source_set', 'member1', 'member2') redis.sadd('destination_set', 'member3') # Move 'member1' from 'source_set' to 'destination_set' redis.smove('source_set', 'destination_set', 'member1') # Verify the contents of both sets (example) print(redis.smembers('source_set')) print(redis.smembers('destination_set')) ``` -------------------------------- ### TypeScript Example for JSON.ARRLEN Source: https://upstash.com/docs/redis/overall/llms-txt A TypeScript code snippet demonstrating how to use the `json.arrlen` method with the Upstash Redis client to retrieve the length of a JSON array. ```APIDOC ## TypeScript Example for JSON.ARRLEN ### Description A TypeScript code snippet demonstrating how to use the `json.arrlen` method with the Upstash Redis client to retrieve the length of a JSON array. ### Method `JSON.ARRLEN` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters - **key** (string) - Required - The key of the JSON document. - **path** (string) - Required - The JSONPath expression to the array. ### Request Example ```ts const length = await redis.json.arrlen("key", "$.path.to.array"); ``` ### Response #### Success Response (200) - **length** (number) - The length of the JSON array. ``` -------------------------------- ### Create Redis Consumer Group with Python Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xgroup_create Demonstrates how to initialize a consumer group for a Redis stream using the Upstash Redis Python client. Examples cover starting from the end of the stream, creating the stream if it does not exist, and starting from the beginning. ```python result = redis.xgroup_create("mystream", "mygroup", "$") ``` ```python result = redis.xgroup_create("newstream", "mygroup", "$", mkstream=True) ``` ```python result = redis.xgroup_create("mystream", "mygroup2", "0-0") ``` -------------------------------- ### GET / - Leaderboard API Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves leaderboard data from a local Cloudflare Worker endpoint and measures request latency. ```APIDOC ## GET / ### Description Send a GET request to a local Cloudflare Worker endpoint to retrieve the current leaderboard and measure the total request latency. ### Method GET ### Endpoint http://127.0.0.1:8787 ### Parameters #### Query Parameters None ### Request Example ```bash curl -w '\n Latency: %{time_total}s\n' http://127.0.0.1:8787 ``` ### Response #### Success Response (200) - **leaderboard_data** (Object | Array) - The retrieved leaderboard data. - **latency** (string) - The measured request latency (e.g., '0.123s'). #### Response Example ```json { "leaderboard": [ {"user": "user1", "score": 100}, {"user": "user2", "score": 90} ] } Latency: 0.123s ``` ``` -------------------------------- ### Navigate to Project Directory (Bash) Source: https://upstash.com/docs/redis/overall/llms-txt Changes the current working directory to a specified project folder. This is a common prerequisite for project setup and development. ```bash cd ratelimit-serverless ``` -------------------------------- ### Initialize Next.js Application Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Next.js project using the latest version of create-next-app and changes the working directory to the new project folder. ```shell npx create-next-app@latest cd my-app ``` -------------------------------- ### GET /websites/upstash-redis Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the value associated with a specified key from Upstash Redis. Returns None if the key is not found. ```APIDOC ## GET /websites/upstash-redis ### Description Return the value of the specified key or `None` if the key doesn't exist. ### Method GET ### Endpoint /websites/upstash-redis ### Parameters #### Query Parameters - **key** (str) - Required - The key to get. ### Request Example ```py # Example theme={"system"} redis.set("key", "value") assert redis.get("key") == "value" ``` ### Response #### Success Response (200) - **value** (any) - The value stored at the key or `None` if the key doesn't exist. #### Response Example ```json { "value": "value" } ``` ``` -------------------------------- ### Create a Basic Search Index Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to initialize a search index named 'profiles' with a string data type, a specific prefix, and a schema definition. It also includes an option to skip the initial scan of existing keys. ```typescript const profiles = await redis.search.createIndex({ name: "profiles", dataType: "string", prefix: "profiles:", skipInitialScan: true, schema: s.object({ name: s.string(), }), }); ``` ```python profiles = redis.search.create_index( name="profiles", data_type="string", prefixes="profiles:", skip_initial_scan=True, schema={ "name": "TEXT", }, ) ``` ```bash SEARCH.CREATE profiles ON STRING PREFIX 1 profiles: SKIPINITIALSCAN SCHEMA name TEXT ``` -------------------------------- ### Redis SET Command Examples (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Python code snippets demonstrating various uses of the Redis SET command, including basic set operations, conditional setting (NX/XX), setting expiration times (EX/PX), and retrieving the previous value. ```python assert redis.set("key", "value") == True assert redis.get("key") == "value" ``` ```python # 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 ``` ```python # Set the key to expire in 10 seconds. assert redis.set("key", "value", ex=10) == True # Set the key to expire in 10000 milliseconds. assert redis.set("key", "value", px=10000) == True ``` ```python # Get the old value stored at the key. assert redis.set("key", "new-value", get=True) == "old-value" ``` -------------------------------- ### Next.js Integration Placeholder Source: https://upstash.com/docs/redis/overall/llms-txt A placeholder snippet for integrating Upstash Redis within a Next.js application. This serves as a starting point for developers to build upon for more complex integrations. ```javascript console.log('This is a placeholder for Next.js code.'); ``` -------------------------------- ### Initialize Redis Client Source: https://upstash.com/docs/redis/overall/llms-txt Creates a reusable Redis client instance for Next.js applications using environment variables for configuration. ```typescript import { Redis } from "@upstash/redis" export const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN, }) ``` -------------------------------- ### URL Shortener Console Output Example Source: https://upstash.com/docs/redis/overall/llms-txt Displays typical console output after running a URL shortener script, showing a generated shortened URL and confirmation of retrieving the original URL. ```text ## Example Console Output of URL Shortener ``` -------------------------------- ### SETRANGE Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the SETRANGE command in Python. It shows setting an initial string value, then overwriting a portion of it using SETRANGE, and finally verifying the updated value. This client-side command execution requires an initialized Redis client instance. ```python # Assuming 'redis' is an initialized Redis client instance # Set an initial value for the key redis.set("key", "Hello World") # Use SETRANGE to overwrite starting from index 6 redis.setrange("key", 6, "Redis") # Get the final value of the key redis.get("key") ``` -------------------------------- ### Initialize Upstash Redis Client from Environment Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to initialize Upstash Redis clients by automatically loading credentials from environment variables for both synchronous and asynchronous usage. ```python # for sync use from upstash_redis import Redis redis = Redis.from_env() # for async use from upstash_redis.asyncio import Redis redis = Redis.from_env() ``` -------------------------------- ### Upstash Redis TOUCH API Request Example Source: https://upstash.com/docs/redis/overall/llms-txt Example request body for the TOUCH API endpoint, which alters the last access time of specified keys. It takes an array of strings representing the keys. ```json { "keys": ["key1", "key2"] } ``` -------------------------------- ### HSCAN Usage Examples (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the HSCAN command in TypeScript for basic scanning, pattern matching, and limiting results. It requires the Upstash Redis client and operates on hash data structures. ```APIDOC ## HSCAN Usage Examples ### Description Scans the hash stored at a key, retrieving elements matching a pattern and limiting the number of results. ### Method N/A (Redis Command) ### Endpoint N/A (Redis Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' is an initialized Upstash Redis client 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"] ``` ### Response #### Success Response (200) - **newCursor** (number) - The cursor for the next iteration. - **fields** (Array) - An array of fields and values. #### Response Example ```json [0, ["id", 1, "username", "chronark", "name", "andreas"]] ``` ### Request Example (with match pattern) ```typescript // Assuming 'redis' is an initialized Upstash Redis client 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"] ``` ### Response #### Success Response (200) - **newCursor** (number) - The cursor for the next iteration. - **fields** (Array) - An array of fields and values matching the pattern. #### Response Example ```json [0, ["username", "chronark"]] ``` ### Request Example (with count limit) ```typescript // Assuming 'redis' is an initialized Upstash Redis client await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const [newCursor, fields] = await redis.hscan("key", 0, { count: 2 }); console.log(fields); // ["id", 1, "name", "andreas", "username", "chronark"] ``` ### Response #### Success Response (200) - **newCursor** (number) - The cursor for the next iteration. - **fields** (Array) - An array of fields and values, limited by count. #### Response Example ```json [0, ["id", 1, "name", "andreas"]] ``` ``` -------------------------------- ### TypeScript MGET Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the values associated with multiple keys from Redis using the `mget` command in TypeScript. It assumes a configured Redis client instance. ```typescript // Assuming 'redis' is a configured Redis client instance const values = await redis.mget("key1", "key2", "key3"); ``` -------------------------------- ### Connect with phpredis (PHP) Source: https://upstash.com/docs/redis/overall/llms-txt Connects to Upstash Redis using the phpredis extension for PHP. It requires the endpoint, port, and password. The example demonstrates setting and getting a key. ```php connect("YOUR_ENDPOINT", "YOUR_PORT"); $redis->auth("YOUR_PASSWORD"); $redis->set("foo", "bar"); print_r($redis->get("foo")); ``` -------------------------------- ### Connect and Use upstash-redis Client with Environment Variables (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to initialize the upstash-redis client by automatically loading credentials from environment variables (UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN). It then performs a GET operation. ```APIDOC ## Connect and Use upstash-redis Client with Environment Variables (TypeScript) ### Description Initializes the upstash-redis client by automatically loading credentials from environment variables (UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN). It then performs a GET operation. ### Method GET (for the `redis.get` operation) ### Endpoint (Not applicable for SDK method) ### Parameters (Environment Variables: UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN) ### Request Example ```typescript 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); } } )(); ``` ### Response #### Success Response (200) - **data** (any) - The value retrieved from the Redis key. #### Response Example ```json "value" ``` ``` -------------------------------- ### Initialize AWS CDK Project Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new AWS CDK application within the current directory, setting up the basic project structure with TypeScript. ```APIDOC ## Initialize AWS CDK Project ### Description Initializes a new AWS CDK application with TypeScript as the chosen language. ### Method Shell command ### Request Example ```bash cdk init app --language typescript ``` ``` -------------------------------- ### Example Redis Pipelining Commands Source: https://upstash.com/docs/redis/overall/llms-txt A set of standard Redis commands (`SET`, `SETEX`, `INCR`, `ZADD`) formatted for submission via the Upstash pipelining API. Pipelining allows for sending multiple commands at once to reduce latency. ```redis SET key1 valuex SETEX key2 13 valuez INCR key1 ZADD myset 11 item1 22 item2 ``` -------------------------------- ### Search Data in Redis Index Source: https://upstash.com/docs/redis/search/getting-started This snippet illustrates how to query and count data within a Redis Search index. It shows filtering by text content in the description and by numerical range in the price field. The examples cover basic filtering and range queries. ```TypeScript const results = await index.query({ filter: { description: "wireless" }, }); const count = await index.count({ filter: { price: { $lt: 150 } }, }); ``` ```Python results = index.query(filter={"description": "wireless"}) count = index.count(filter={"price": {"$lt": 150}}) ``` ```Redis CLI SEARCH.QUERY products '{"description": "wireless"}' SEARCH.COUNT products '{"price": {"$lt": 150}}' ``` -------------------------------- ### SCARD - Get Set Size Source: https://upstash.com/docs/redis/overall/llms-txt Returns the number of elements in a set stored at the specified key using the SCARD command. ```APIDOC ## SCARD ### Description Return how many members are in a set. ### Method GET ### Endpoint /SCARD ### Parameters #### Query Parameters - **key** (str) - Required - The key of the set. ### Request Example ``` GET /SCARD?key=my_set ``` ### Response #### Success Response (200) - **count** (int) - Required - How many members are in the set. #### Response Example ```json { "count": 3 } ``` ``` -------------------------------- ### Testing Leaderboard API with cURL (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates testing the leaderboard API locally using cURL. Shows examples for adding new scores via POST requests and retrieving the leaderboard via GET requests, including latency measurement. ```shell curl -X POST http://127.0.0.1:8787\?player\=messi\&score\=13 curl -X POST http://127.0.0.1:8787\?player\=ronaldo\&score\=17 curl -X POST http://127.0.0.1:8787\?player\=benzema\&score\=18 ``` ```shell curl -w '\n Latency: %{time_total}s\n' http://127.0.0.1:8787 ``` -------------------------------- ### JSON.FORGET Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `JSON.FORGET` command with the Python client for Upstash Redis, demonstrating how to delete a specific path within a JSON document. ```python # Assuming 'redis' is an initialized Upstash Redis client # Assuming 'key' and the JSON structure are defined # Delete the value at the path '$.path.to.value' redis.json().forget(key, "$.path.to.value") ``` -------------------------------- ### GET /:key Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the value associated with a given key. Supports base64 encoded responses by setting the 'Upstash-Encoding' header. ```APIDOC ## GET /:key ### Description Retrieves the value associated with a given key. Supports base64 encoded responses. ### Method GET ### Endpoint `/` ### Headers - **Authorization** (string) - Required - Bearer token for authentication. - **Upstash-Encoding** (string) - Optional - Specifies the encoding for the response. Set to `base64` for base64 encoded output. ### Request Example ```shell curl https://your-upstash-redis-url.com/GET/foo \ -H "Authorization: Bearer YOUR_AUTH_TOKEN" \ -H "Upstash-Encoding: base64" ``` ### Response #### Success Response (200) - **value** (string) - The value of the key, potentially base64 encoded if requested. #### Response Example ```json { "result": "encoded_value_here" } ``` ``` -------------------------------- ### Initialize Redis Data via CLI Source: https://upstash.com/docs/redis/overall/llms-txt Populates a Redis database with location-specific greeting messages using standard redis-cli commands. ```shell set GB "Ey up?" set US "Yo, what’s up?" set TR "Naber dostum?" set DE "Was ist los?" ``` -------------------------------- ### Ratelimit blockUntilReady Usage Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use ratelimit.blockUntilReady to create a ratelimiter and wait for a request to be allowed. It shows initializing a ratelimiter and handling the success or failure of the blockUntilReady call. ```APIDOC ## Ratelimit blockUntilReady Usage Example (TypeScript) ### Description This example shows how to set up a rate limiter using `blockUntilReady` and wait for a request to be permitted. It handles the outcome of the `blockUntilReady` operation. ### Method `ratelimit.blockUntilReady(identifier, timeout)` ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ts // 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, }); // `blockUntilReady` returns a promise that resolves as soon as the request is allowed to be processed, or after 30 seconds const { success } = await ratelimit.blockUntilReady("id", 30_000); if (!success) { return "Unable to process, even after 30 seconds"; } doExpensiveCalculation(); return "Here you go!"; ``` ### Response #### Success Response - `success` (boolean) - Indicates if the request was allowed within the timeout period. ``` -------------------------------- ### SDIFFSTORE Command API Reference (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Detailed documentation for the SDIFFSTORE command in TypeScript, outlining its required arguments and the structure of its response. ```APIDOC ## SDIFFSTORE Command API Reference ### Description Computes the difference between sets and stores the result in a new set. ### Method N/A (Redis Command) ### Endpoint N/A (Redis Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' is an initialized Upstash Redis client await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); const stored = await redis.sdiffstore("dest", "set1", "set2"); console.log(stored); // 2 (number of elements in the difference) ``` ### Response #### Success Response (200) - **stored** (number) - The number of elements in the destination set. #### Response Example ```json 2 ``` ``` -------------------------------- ### Connect and Execute Commands with redis-cli Source: https://upstash.com/docs/redis/overall/getstarted Demonstrates how to establish a secure TLS connection to an Upstash Redis instance using the redis-cli tool and execute basic Redis commands like SET, GET, and INCR. ```bash redis-cli --tls -a PASSWORD -h ENDPOINT -p PORT set counter 0 get counter incr counter incr counter ``` -------------------------------- ### Manual Redis Client Initialization (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to manually instantiate the Redis client by providing the URL and token directly. This bypasses environment variable auto-detection. ```typescript new Redis({ url: "https://****.upstash.io", token: "********", }); ``` -------------------------------- ### Get Hash Field Count with Python Source: https://upstash.com/docs/redis/overall/llms-txt This example illustrates how to get the number of fields in a hash stored in Upstash Redis using Python. It covers setting hash fields with `HSET` and then retrieving the count using `HLEN`. ```APIDOC ## Get Hash Field Count with Python (Upstash Redis) ### Description Demonstrates how to use the HLEN command with Upstash Redis in Python to retrieve the number of fields in a hash. It includes setting fields using HSET and then verifying the count with HLEN. ### Method Client-side command execution ### Endpoint N/A (Client-side command) ### Parameters #### HLEN Parameters - **key** (string) - Required - The key of the hash. #### HSET Parameters (for setup) - **key** (string) - Required - The key of the hash. - **mapping** (dict) - Required - A dictionary of field-value pairs to set. ### Request Example (Code Snippet) ```python # Assuming 'redis' is an initialized Upstash Redis client instance # Check initial count (should be 0 if hash does not exist or is empty) assert redis.hlen("myhash") == 0 # Set fields in the hash redis.hset("myhash", mapping={ "field1": "Hello", "field2": "World" }) # Get the count of fields in the hash assert redis.hlen("myhash") == 2 ``` ### Response #### Success Response (HLEN) - **integer** - The number of fields in the hash. ``` -------------------------------- ### Monitor Upstash Redis Commands (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ioredis client to connect to an Upstash Redis database and set up a real-time monitor. ```APIDOC ## Monitor Upstash Redis Commands (TypeScript) ### Description Demonstrates how to use the `ioredis` client to connect to an Upstash Redis database and set up a real-time monitor. It listens for the 'monitor' event, logging details of each executed command to the console. ### Request Example ```ts const monitor = await redis.monitor() monitor.on("monitor", (time, args, source, database) => { console.log(time, args, source, database) }) ``` ``` -------------------------------- ### XREVRANGE Command Examples (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using the XREVRANGE command in Python to fetch stream entries in reverse order, with options to limit the count or specify an ID range. ```python result = redis.xrevrange("mystream", "+", "-") ``` ```python result = redis.xrevrange("mystream", "+", "-", count=2) ``` ```python result = redis.xrevrange("mystream", end="1638360173533-2", start="1638360173533-0") ``` -------------------------------- ### Install isomorphic-fetch for Node.js < v17 Source: https://upstash.com/docs/redis/overall/llms-txt If running on Node.js v17 or earlier without a native fetch polyfill, install the 'isomorphic-fetch' package to resolve 'ReferenceError: fetch is not defined'. This is often provided by platforms like Vercel or Netlify, but bare Node.js installations require manual addition. ```bash npm i isomorphic-fetch ``` -------------------------------- ### LRANGE Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the Redis LRANGE command, outlining its required parameters (key, start, end indices) and the expected array response. ```plaintext ## LRANGE Command ### Description Returns the specified elements of the list stored at key. ### Method POST (Implied by command format) ### Endpoint /redis/v1/command (Implied by context) ### Arguments #### Request Body - **key** (string) - Required - The key of the list. - **start** (integer) - Required - The starting index of the range to return. Use negative numbers to specify offsets starting at the end of the list. - **end** (integer) - Required - The ending index of the range to return. Use negative numbers to specify offsets starting at the end of the list. ``` -------------------------------- ### Initialize and Implement Ratelimit (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates initializing the Ratelimit instance with Redis and applying it to an endpoint. It uses a sliding window algorithm to control request flow. ```typescript import { Ratelimit } from "@upstash/ratelimit"; import { Redis } from "@upstash/redis"; const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(10, "10 s"), analytics: true, prefix: "@upstash/ratelimit", }); const identifier = "api"; const { success } = await ratelimit.limit(identifier); if (!success) { return "Unable to process at this time"; } doExpensiveCalculation(); return "Here you go!"; ``` -------------------------------- ### Initialize Upstash Redis Client from Environment (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to initialize Upstash Redis clients by automatically loading credentials from environment variables. Supports both synchronous and asynchronous clients. ```APIDOC ## Initialize Upstash Redis Client from Environment (Python) ### Description Shows how to initialize Upstash Redis clients by automatically loading credentials from environment variables. Supports both synchronous and asynchronous clients. ### Method Initialization ### Endpoint N/A ### Parameters None ### Request Example ```python # for sync use from upstash_redis import Redis redis = Redis.from_env() # for async use from upstash_redis.asyncio import Redis redis = Redis.from_env() ``` ### Response #### Success Response (200) - **redis** (Redis client instance) - An initialized Upstash Redis client instance. ``` -------------------------------- ### Building React Native Apps with AWS Lambda and Serverless Redis Source: https://upstash.com/docs/redis/overall/llms-txt Details how to build React Native mobile applications powered by AWS Lambda and Upstash Redis. This example focuses on creating serverless backends for mobile apps. ```javascript import TagFilters from "../../src/components/Filter.js" Building React Native Apps Backed by AWS Lambda and Serverless Redis ``` -------------------------------- ### Scoreboard with Upstash Redis (React Example) Source: https://upstash.com/docs/redis/overall/llms-txt Provides example functions for updating and retrieving scores in a scoreboard stored in Upstash Redis using React and JavaScript. It utilizes ZADD to update scores and ZREVRANGE to fetch top scores, requiring an initialized Redis client. ```javascript // Example score update and retrieval async function updateScore(playerName, score) { await redis.zadd('scoreboard', { score: score, value: playerName }); } async function getTopScores(count) { return await redis.zrevrange('scoreboard', 0, count - 1, { withScores: true }); } ``` -------------------------------- ### Initialize Upstash Redis Client Source: https://upstash.com/docs/redis/overall/llms-txt Explains how to initialize the Upstash Redis client in Node.js or browser environments using environment variables or explicit configuration. ```APIDOC ## Initialize Upstash Redis Client ### Description Initializes the Upstash Redis client for Node.js and browser environments. ### Usage Configuration can be loaded from explicit URL/token environment variables or directly using `Redis.fromEnv()`. ### Example (Explicit Configuration) ```ts import { Redis } from "@upstash/redis" const redis = new Redis({ url: "", token: "", }) ``` ### Example (From Environment Variables) ```ts import { Redis } from "@upstash/redis" // Loads configuration from UPSTASH_REDIS_URL and UPSTASH_REDIS_TOKEN environment variables const redis = Redis.fromEnv() ``` ``` -------------------------------- ### Upstash Redis GETSET Command Example (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/string/getset Demonstrates the usage of the GETSET command in Upstash Redis using Python. This snippet shows how to set an initial value and then use GETSET to retrieve the old value while setting a new one. It assumes a 'redis' client object is already configured. ```python redis.set("key", "old-value") assert redis.getset("key", "newvalue") == "old-value" ``` -------------------------------- ### ZREM Command Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZREM command in Python with the Upstash Redis client. It shows adding initial members to a sorted set and then removing specific members, asserting the count of successfully removed members. ```python ## ZREM Command Example (Python) ### Description Demonstrates how to use the ZREM command in Python with the Upstash Redis client. It shows adding initial members to a sorted set and then removing specific members, asserting the count of successfully removed members. ``` -------------------------------- ### Initialize Node.js Project for AWS App Runner Source: https://upstash.com/docs/redis/overall/llms-txt Creates a project directory and installs the ioredis client for use with Upstash Redis in AWS App Runner environments. ```bash mkdir app_runner_example cd app_runner_example npm init npm install ioredis ``` -------------------------------- ### BITOP Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the Redis BITOP command, including its supported operations, required keys, and the format of its response. ```APIDOC ## BITOP Command API Reference ### Description Performs bitwise operations on multiple keys (or Redis strings) and stores the result in a destination key. ### Method `BITOP operation destinationKey key [key ...]` ### Endpoint Not applicable (Redis command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```APIDOC BITOP AND destkey key1 key2 BITOP OR destkey key1 key2 BITOP XOR destkey key1 key2 BITOP NOT destkey key1 ``` ### Response #### Success Response - `type` (integer) - The size of the string stored in the destination key. ``` -------------------------------- ### Fetch data in Next.js Server Component Source: https://upstash.com/docs/redis/quickstarts/nextjs-app-router Demonstrates how to use the initialized Redis client within a Next.js server component to retrieve data. ```typescript import { redis } from "@/lib/redis" const Page = async () => { const count = await redis.get("count") return

count: {count}

} export default Page ``` -------------------------------- ### GETRANGE Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Detailed API documentation for the GETRANGE Redis command, outlining its required arguments (key, start, end indices) and the expected string response. ```APIDOC ## GETRANGE ### Description Return a substring of value at the specified key. ### Method GETRANGE ### Endpoint GETRANGE ### Parameters #### Path Parameters - **key** (str) - Required - The key to get. - **start** (int) - Required - The start index of the substring. - **end** (int) - Required - The end index of the substring. ### Response #### Success Response (200) - **response** (str) - Required - The substring. ### Response Example ```json { "response": "substring" } ``` ``` -------------------------------- ### LPUSH Command Usage Example in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the LPUSH command with a Redis client in Python to add multiple elements to the head of a list, and then verifies the list's content and order using LRANGE. ```APIDOC ## LPUSH Command Usage Example in Python ### Description Adds elements to the head of a list and verifies the list's content and order. ### Method ``` redis.lpush(key, element1, element2, ...) ``` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python assert redis.lpush("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["three", "two", "one"] ``` ### Response #### Success Response (200) Integer representing the number of elements added. #### Response Example ```json 3 ``` ``` -------------------------------- ### Example Usage of LRANGE with Upstash Redis in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `lpush` command to populate a Redis list and then retrieve a specific range of elements using the `lrange` command with an Upstash Redis client in TypeScript. ```APIDOC ## Example Usage of LRANGE with Upstash Redis in TypeScript ### Description Demonstrates how to use the `lpush` command to populate a Redis list and then retrieve a specific range of elements using the `lrange` command with an Upstash Redis client in TypeScript. ### Method N/A (SDK Example) ### Endpoint N/A (SDK Example) ### Parameters None ### Request Example ```ts await redis.lpush("key", "a", "b", "c"); const elements = await redis.lrange("key", 1, 2); console.log(elements) // ["b", "c"] ``` ### Response N/A (SDK Example) ``` -------------------------------- ### LRANGE Command Documentation and TypeScript Example Source: https://upstash.com/docs/redis/overall/llms-txt Details the LRANGE command for retrieving specified elements from a Redis list. Includes parameters, request structure, response format, and a conceptual TypeScript request example using the Upstash Redis client. ```typescript // Conceptual example using Upstash Redis client await redis.lpush("key", "a", "b", "c"); const elements = await redis.lrange("key", 1, 2); console.log(elements); // Expected output: ["b", "c"] ``` -------------------------------- ### Import Redis Client in Deno Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to import the Redis client from the Upstash Redis package in a Deno environment. Ensure Deno is installed and configured. ```APIDOC ## Import Redis Client in Deno ### Description Demonstrates how to import the Redis client from the Upstash Redis package in a Deno environment. Ensure Deno is installed and configured. ### Method Import ### Endpoint N/A ### Parameters None ### Request Example ```typescript import { Redis } from "https://deno.land/x/upstash_redis/mod.ts"; ``` ### Response #### Success Response (200) - **Redis** (Class) - The Redis client class from the Upstash package. ``` -------------------------------- ### XLEN - Get Stream Length Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the number of entries within a Redis stream. If the specified stream does not exist, the command returns 0. ```APIDOC ## GET /websites/upstash-redis/xlen ### Description Returns the number of entries inside a stream. If the stream does not exist, it returns 0. ### Method GET ### Endpoint /websites/upstash-redis/xlen ### Parameters #### Query Parameters - **key** (str) - Required - The key of the stream. ### Request Example ```http GET /websites/upstash-redis/xlen?key=mystream ``` ### Response #### Success Response (200) - **count** (int) - The number of entries in the stream. Returns 0 if the stream does not exist. #### Response Example ```json { "count": 10 } ``` ``` -------------------------------- ### Initialize Serverless Golang Application Source: https://upstash.com/docs/redis/overall/llms-txt A basic template for a Go application intended for serverless environments like AWS Lambda, integrated with Upstash Redis. ```go package main import "fmt" func main() { fmt.Println("This is a placeholder for Go code.") } ``` -------------------------------- ### ZRANGE Command Examples (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates using the ZRANGE command in TypeScript to retrieve members from a Redis sorted set. Examples cover basic range retrieval, retrieving members with their scores, and sorting by score. Requires a Redis client instance and involves asynchronous operations. ```APIDOC ## ZRANGE Command Examples (TypeScript) ### Description Illustrates using the ZRANGE command in TypeScript to retrieve members from a Redis sorted set. Examples cover basic range retrieval, retrieving members with their scores, and sorting by score. Requires a Redis client instance and involves asynchronous operations. ### Method POST (Implicit via Redis Client) ### Endpoint (Not Applicable - Client-side command execution) ### Parameters (Refer to Upstash Redis documentation for ZRANGE command parameters) ### Request Example ```typescript await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" }, ) const res = await redis.zrange("key", 1, 3) console.log(res) // ["m2"] ``` ### Response (Output depends on the specific ZRANGE parameters and data in the sorted set) #### Success Response - **Array of members** (string[]) - Members within the specified range. - **Array of members with scores** (Array<[string, number]>) - Members and their scores within the specified range. #### Response Example ```json // For basic ZRANGE ["m2"] // For ZRANGE with scores ["m2", 2] ``` ``` -------------------------------- ### Initialize Upstash Redis Client in Vercel Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to initialize the Upstash Redis client in a Vercel serverless function using environment variables. It includes basic set and get operations to verify connectivity. ```typescript const { Redis } = require("@upstash/redis"); module.exports = async (req, res) => { const redis = Redis.fromEnv(); await redis.set("foo", "bar"); const bar = await redis.get("foo"); res.json({ body: `foo: ${bar}`, }); }; ``` -------------------------------- ### Apply Rate Limit Using IP Address (JSON) Source: https://upstash.com/docs/redis/integrations/ratelimit/strapi/configurations This example configures a rate limit based on the client's IP address. It applies to all routes for GET and POST requests, with a limit of 10 tokens per 20 seconds using the fixed-window algorithm. Requires UPSTASH_REDIS_REST_TOKEN and UPSTASH_REDIS_REST_URL environment variables. ```json { "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" } } } ``` -------------------------------- ### LPUSH Command Example in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using the LPUSH command with the Upstash Redis client in TypeScript to insert values at the head of a list. Shows multiple pushes and the resulting list length. ```typescript // Assuming 'redis' is an initialized Upstash Redis client await redis.lpush("mylist", "value1", "value2"); const length = await redis.llen("mylist"); console.log(length); // Output will depend on previous list state ``` -------------------------------- ### Navigate to Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt Shell command to change the working directory to the project folder. ```shell cd counter-serverless ``` -------------------------------- ### Upstash Redis ZRANGE Command Examples (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZRANGE command in Upstash Redis with Python. It covers basic range retrieval, reversing the order, sorting by score, and including scores in the output. Requires the 'redis' library. ```APIDOC ## Upstash Redis ZRANGE Command Examples (Python) ### Description Demonstrates how to use the ZRANGE command in Upstash Redis with Python. It covers basic range retrieval, reversing the order, sorting by score, and including scores in the output. Requires the 'redis' library. ### Method SDK Method (Python) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **key** (string) - Required - The key of the sorted set. - **start** (integer) - Required - The starting index of the range. - **stop** (integer) - Required - The ending index of the range. - **rev** (boolean) - Optional - If true, reverses the order. - **sortby** (string) - Optional - Specifies sorting criteria (e.g., 'BYSCORE'). - **withscores** (boolean) - Optional - If true, includes scores in the output. ### Request Example ```python import redis redis_client = redis.Redis(host='YOUR_REDIS_HOST', port=YOUR_REDIS_PORT, password='YOUR_REDIS_PASSWORD') # Example 1: Basic ZRANGE redis_client.zadd("myset", {"a": 1, "b": 2, "c": 3}) print(f"Basic ZRANGE: {redis_client.zrange('myset', 0, 1)}") # Example 2: ZRANGE with reverse order print(f"Reverse ZRANGE: {redis_client.zrange('myset', 0, 1, rev=True)}") # Example 3: ZRANGE sorted by score print(f"Sorted ZRANGE: {redis_client.zrange('myset', 0, 1, sortby='BYSCORE')}") # Example 4: ZRANGE with scores print(f"Zrange with scores: {redis_client.zrange('myset', 0, 1, withscores=True)}") ``` ### Response #### Success Response (200) - **elements** (list) - A list of elements within the specified range, potentially with scores. #### Response Example ```json [b'a'] ``` ``` -------------------------------- ### Install @upstash/redis Dependency Source: https://upstash.com/docs/redis/overall/llms-txt Adds the `@upstash/redis` package as a project dependency using npm. This is essential for Node.js applications to interact with Upstash Redis. ```json { "dependencies": { "@upstash/redis": "latest" } } ``` -------------------------------- ### Install FastAPI and Upstash Redis (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary Python packages for FastAPI and the Upstash Redis client. Ensure you have Python and pip installed. ```APIDOC ## Install FastAPI and Upstash Redis (Shell) ### Description Installs the FastAPI web framework and the Upstash Redis Python client using pip. ### Method Command Line Interface (CLI) ### Endpoint N/A (CLI commands) ### Parameters None ### Request Example ```shell pip install fastapi pip install upstash-redis ``` ### Response - The command output will show the installation progress and confirmation of successful package installation. ``` -------------------------------- ### POST /redis/sdiffstore Source: https://upstash.com/docs/redis/overall/llms-txt Writes the difference between sets to a new set. ```APIDOC ## POST /redis/sdiffstore ### Description Write the difference between sets to a new set ### Method APICALL ### Endpoint /redis/sdiffstore ### Parameters #### Query Parameters - **destination** (string) - Required - The key of the set to store the resulting set in. - **keys** (string[]) - Required - The keys of the sets to perform the difference operation on. ### Request Example ```json { "destination": "new_set_key", "keys": ["set1", "set2"] } ``` ### Response #### Success Response (200) - **Type** (TValue[]) - The members of the resulting set. #### Response Example ```json ["member1", "member2"] ``` ``` -------------------------------- ### HSCAN Command Usage Examples (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates various ways to use the HSCAN command with Upstash Redis in TypeScript. Includes basic scanning, filtering by pattern, and limiting the number of returned fields. Assumes an SDK context for API calls. ```typescript const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.fixedWindow(10, "10 s"), }); ``` ```typescript const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }) ], limiter: MultiRegionRatelimit.fixedWindow(10, "10 s"), }); ``` -------------------------------- ### Initialize Upstash Redis Client in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to initialize an Upstash Redis client in Node.js or browser environments using environment variables or explicit configuration. This allows for flexible setup depending on the deployment environment. ```typescript import { Redis } from "@upstash/redis" const redis = new Redis({ url: "", token: "", }) ``` ```typescript import { Redis } from "@upstash/redis" // Loads configuration from UPSTASH_REDIS_URL and UPSTASH_REDIS_TOKEN environment variables const redis = Redis.fromEnv() ``` -------------------------------- ### Install Python Libraries for Chat App Source: https://upstash.com/docs/redis/overall/llms-txt Installs Flask, Flask-SocketIO, and the Redis library using pip. These are essential dependencies for building the real-time chat application. ```bash pip install flask flask-socketio redis ``` -------------------------------- ### RPUSH Command API Example Source: https://upstash.com/docs/redis/overall/llms-txt Documents the RPUSH command API, detailing its purpose to push an element at the end of a list. It outlines the required path parameters (key, elements) and the response structure, which is the length of the list after the operation. ```json { "key": "myList", "elements": ["a", "b", "c"] } ``` -------------------------------- ### Initialize Cloudflare Worker Project (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Cloudflare Worker project using the `wrangler init` CLI. This process includes setting up the project directory, selecting a template, choosing a language (TypeScript), and installing dependencies. ```APIDOC ## Initialize Cloudflare Worker Project ### Description Initializes a new Cloudflare Worker project using the `wrangler init` CLI. This process includes setting up the project directory, selecting a template, choosing a language (TypeScript), and installing dependencies. ### Method CLI Command ### Endpoint N/A ### Parameters N/A ### Request Example ```shell npx wrangler init ``` ### Response (Output of the CLI command, guiding through project setup) ``` -------------------------------- ### Test Leaderboard API with cURL (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Provides shell commands to interact with a leaderboard API. Demonstrates POST requests to add scores and GET requests to retrieve data with latency measurement. ```shell curl -X POST http://127.0.0.1:8787?player=messi&score=13 curl -X POST http://127.0.0.1:8787?player=ronaldo&score=17 curl -X POST http://127.0.0.1:8787?player=benzema&score=18 curl -w '\n Latency: %{time_total}s\n' http://127.0.0.1:8787 ``` -------------------------------- ### Connect to Upstash Redis with Node.js Source: https://upstash.com/docs/redis/overall/llms-txt Initializes the Redis client using environment variables and performs a basic set operation. Requires the @upstash/redis package. ```javascript import { Redis } from "@upstash/redis"; const redis = new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN, }); const data = await redis.set("foo", "bar"); ``` -------------------------------- ### Upstash Redis Worker Code Example (TypeScript/JavaScript) Source: https://upstash.com/docs/redis/overall/llms-txt A Cloudflare Worker template demonstrating how to connect to Upstash Redis and increment a counter. It uses environment variables for credentials and the Upstash Redis SDK. ```APIDOC ## Upstash Redis Cloudflare Worker Example ### Description This example shows how to create a Cloudflare Worker that connects to Upstash Redis and increments a counter. ### Method N/A (Worker Fetch Event) ### Endpoint N/A (Worker Endpoint) ### Parameters #### Environment Variables - **UPSTASH_REDIS_REST_URL** (string) - Required - The URL for your Upstash Redis instance. - **UPSTASH_REDIS_REST_TOKEN** (string) - Required - The token for your Upstash Redis instance. ### Request Example (TypeScript) ```typescript 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 })); }, } satisfies ExportedHandler; ``` ### Request Example (JavaScript) ```javascript import { Redis } from "@upstash/redis/cloudflare"; export default { async fetch(request, env, ctx) { const redis = Redis.fromEnv(env); const count = await redis.incr("counter"); return new Response(JSON.stringify({ count })); }, }; ``` ### Response #### Success Response (200) - **count** (number) - The current value of the counter after incrementing. ``` -------------------------------- ### External API Integration with Redis Caching (Elixir) Source: https://upstash.com/docs/redis/overall/llms-txt An Elixir example demonstrating how to fetch weather data from an external API, process it, and cache the response in Redis. This reduces redundant API calls. ```APIDOC ## External API Integration with Redis Caching (Elixir) ### Description This example shows an Elixir function `fetch_weather_from_api` that retrieves weather data from an external API. It uses an environment variable for the API key, caches the response in Redis for 8 hours, and then returns the processed weather information. ### Method GET (for external API call) POST (for caching in Redis) ### Endpoint * External API: `http://api.weatherapi.com/v1/current.json` * Redis Cache: (Assumed Upstash Redis endpoint) ### Parameters * **location** (string) - Required - The location for which to fetch weather data. * **WEATHER_API_KEY** (environment variable) - Required - Your API key for the WeatherAPI. ### Request Example (Conceptual - Elixir Function Call) ```elixir fetch_weather_from_api("London") ``` ### Response #### Success Response (200 for API, Redis set for cache) - **weather_info** (map) - Processed weather data. #### Response Example (Conceptual) ```elixir {:ok, %{ "location": %{"name" => "London"}, "current" => %{"temp_c" => 15.0, "condition" => %{"text" => "Partly cloudy"}} }} ``` ``` -------------------------------- ### Redis XCLAIM: Basic Message Claiming (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the XCLAIM command in TypeScript to claim messages from a Redis stream. This example shows the basic usage without any optional parameters. ```APIDOC ## Redis XCLAIM: Basic Message Claiming (TypeScript) ### Description Demonstrates how to use the XCLAIM command in TypeScript to claim messages from a Redis stream. This example shows the basic usage without any optional parameters. ### Method XCLAIM ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters - **key** (string) - Required - The key of the stream. - **group** (string) - Required - The name of the consumer group. - **consumer** (string) - Required - The name of the consumer. - **min-idle-time** (number) - Required - The minimum idle time in milliseconds for a message to be considered for claiming. - **ids** (string[]) - Required - An array of message IDs to claim. ### Request Example ```typescript const result = await redis.xclaim( "mystream", "mygroup", "consumer1", 60000, ["1638360173533-0", "1638360173533-1"] ); ``` ### Response #### Success Response (200) - **Array of messages** - The messages that were successfully claimed. ``` -------------------------------- ### TypeScript JSON.DEL Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `redis.json.del` method in TypeScript to delete a specific path within a JSON document stored in Upstash Redis. ```APIDOC ## TypeScript JSON.DEL Example ### Description Deletes a specific path within a JSON document stored in Upstash Redis using the `json.del` method. ### Method `POST` ### Endpoint /json/del ### Parameters #### Request Body - **key** (string) - Required - The key of the JSON document. - **path** (string) - Required - The JSON path to the value to delete. ### Request Example ```json { "key": "key", "path": "$.path.to.value" } ``` ### Response #### Success Response (200) - **(integer)** - The number of paths that were removed. #### Response Example ```json 1 ``` ### Code Example ```ts await redis.json.del("key", "$.path.to.value"); ``` ``` -------------------------------- ### TypeScript: Ratelimit blockUntilReady Usage Example Source: https://upstash.com/docs/redis/overall/llms-txt An example demonstrating the `blockUntilReady` method for rate limiting in TypeScript. It shows how to wait for a request to be processed within a timeout, handling cases where it cannot be processed. ```typescript // 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, }); // `blockUntilReady` returns a promise that resolves as soon as the request is allowed to be processed, or after 30 seconds const { success } = await ratelimit.blockUntilReady("id", 30000); if (!success) { return "Unable to process, even after 30 seconds"; } doExpensiveCalculation(); return "Here you go!"; ``` -------------------------------- ### Example Console Output of URL Shortener Source: https://upstash.com/docs/redis/overall/llms-txt This snippet displays a typical console output after successfully running the `url_shortener.py` script. It shows the generated shortened URL and confirms the successful retrieval of the original URL using the short code. ```APIDOC ## Example Console Output of URL Shortener ### Description This snippet displays a typical console output after successfully running the `url_shortener.py` script. It shows the generated shortened URL and confirms the successful retrieval of the original URL using the short code. ### Method (Not Applicable - This describes a script's output) ### Endpoint (Not Applicable) ### Parameters (Not Applicable) ### Request Example (Not Applicable) ### Response #### Example Output (This is a textual representation of console output) #### Response Example ``` Generated Short URL: http://short.ly/AbCdEf Original URL retrieved: https://www.example.com/long/url/path ``` ``` -------------------------------- ### Initialize Redis Client from Environment Variables Source: https://upstash.com/docs/redis/howto/connectwithupstashredis Shows how to initialize the Redis client automatically using environment variables. This is the recommended approach for secure credential management in serverless deployments. ```typescript 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); } })(); ``` -------------------------------- ### SDIFFSTORE Command Example (API) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the API structure for the SDIFFSTORE command in Upstash Redis. It computes the difference between sets and stores the result in a new set using a POST request. ```json { "command": "SDIFFSTORE", "args": ["destination_key", "key1", "key2"] } ``` -------------------------------- ### Initialize Cloudflare Worker Project (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Cloudflare Worker project using the `wrangler init` CLI. This process includes setting up the project directory, selecting a template, choosing a language (TypeScript), and installing dependencies. ```shell npx wrangler init ╭ Create an application with Cloudflare Step 1 of 3 │ ├ In which directory do you want to create your application? │ dir ./greetings-cloudflare │ ├ What would you like to start with? │ category Hello World example │ ├ Which template would you like to use? │ type Hello World Worker │ ├ Which language do you want to use? │ lang TypeScript │ ├ Copying template files │ files copied to project directory │ ├ Updating name in `package.json` │ updated `package.json` │ ╰ Application created ╭ Configuring your application for Cloudflare Step 2 of 3 │ ├ Installing @cloudflare/workers-types │ installed via npm │ ├ Adding latest types to `tsconfig.json` │ added @cloudflare/workers-types/2023-07-01 │ ├ Retrieving current workerd compatibility date │ compatibility date 2024-10-22 │ ├ Do you want to use git for version control? │ no git │ ╰ Application configured ``` -------------------------------- ### Initialize Upstash Redis Client (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates initializing both synchronous and asynchronous Upstash Redis clients using direct URL and token credentials. Replace placeholders with your actual Upstash credentials. ```python # for sync client from upstash_redis import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") # for async client from upstash_redis.asyncio import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") ``` -------------------------------- ### Install Redis Search Dependencies Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary packages to enable Redis Search functionality within a node-redis project. ```bash npm install @upstash/search-redis redis ``` -------------------------------- ### Configure Dockerfile for Node.js Source: https://upstash.com/docs/redis/overall/llms-txt Standard Dockerfile instructions to install npm dependencies and copy local source code into the container image. ```dockerfile RUN npm install COPY . ./ ``` -------------------------------- ### Initialize Redis Data Source: https://upstash.com/docs/redis/tutorials/coin_price_list Populates the Redis database with a list of coin objects using the RPUSH command via Redis CLI. ```shell rpush coins '{ "name" : "Bitcoin", "price": 56819, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/1.png"}' '{ "name" : "Ethereum", "price": 2130, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png"}' '{ "name" : "Cardano", "price": 1.2, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/2010.png"}' '{ "name" : "Polkadot", "price": 35.96, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/6636.png"}' '{ "name" : "Stellar", "price": 0.506, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/512.png"}' ``` -------------------------------- ### Setup Python Conda Environment Source: https://upstash.com/docs/redis/overall/llms-txt Creates and activates a Conda environment with Python 3.12 and installs project dependencies. ```shell conda create --name vercel-django python=3.12 conda activate vercel-django pip install -r requirements.txt ``` -------------------------------- ### Execute ZPOPMAX Command via API and Python Source: https://upstash.com/docs/redis/overall/llms-txt Documents the ZPOPMAX command for removing members from a sorted set, including the REST API request body and a Python client example. ```JSON { "command": "zpopmax", "key": "", "count": "" } ``` ```Python result = redis.zpopmax('my_sorted_set', count=1) ``` -------------------------------- ### Get Multiple JSON Values (JSON.MGET) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the redis.json.mget method in TypeScript to retrieve values from multiple JSON documents at a specified path. ```APIDOC ## Get Multiple JSON Values (JSON.MGET) ### Description Retrieves values from multiple JSON documents at a specified path using the `redis.json.mget` method. ### Method `redis.json.mget(path, keys)` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const result = await redis.json.mget('$.username', ['user:1', 'user:2']); // result will be ['"Alice"', '"Bob"'] ``` ### Response #### Success Response - `result` (array) - An array of JSON values retrieved from the specified keys and path. ``` -------------------------------- ### BITOP Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Documentation for the Redis BITOP command, detailing its operations (AND, OR, XOR, NOT), required arguments (destkey, keys), and the integer response indicating the size of the stored string. ```plaintext BITOP Command: Description: Perform bitwise operations on multiple keys and store the result in a destination key. Arguments: operation: AND | OR | XOR | NOT (required) Description: Specifies the type of bitwise operation to perform. destkey: str (required) Description: The key to store the result of the operation in. keys: *List[str] (required) Description: One or more keys to perform the operation on. Response: type: int (required) Description: The size of the string stored in the destination key. ``` -------------------------------- ### ZDIFFSTORE Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZDIFFSTORE command in Upstash Redis to compute the difference between sets and store the result in a new key. This function requires the 'redis' client instance and takes the destination key, the number of keys to compare, and the keys themselves as arguments. ```APIDOC ## ZDIFFSTORE Command Example (TypeScript) ### Description Demonstrates how to use the ZDIFFSTORE command in Upstash Redis to compute the difference between sets and store the result in a new key. This function requires the 'redis' client instance and takes the destination key, the number of keys to compare, and the keys themselves as arguments. ### Method SDK Method (TypeScript) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **destination** (string) - Required - The key where the result will be stored. - **numkeys** (integer) - Required - The number of keys to compare. - **keys** (*string) - Required - The keys of the sets to compare. ### Request Example ```typescript const values = await redis.zdiffstore("destination", 2, "key1", "key2"); ``` ### Response #### Success Response (200) - **count** (integer) - The number of elements in the difference. #### Response Example ```json 5 ``` ``` -------------------------------- ### TypeScript SADD Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `SADD` command with the Upstash Redis client in TypeScript, showing the expected return values for different scenarios. It assumes a configured Redis client instance. ```typescript await redis.sadd(key, member1, member2, ...); ``` -------------------------------- ### Initialize AWS SAM Project (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Command to initialize a new AWS Serverless Application Model (SAM) project. This command typically prompts the user for template selection, runtime, and project name, setting up the foundational structure for a serverless application. ```shell sam init ``` -------------------------------- ### Get List Length with LLEN (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to get the number of elements in a Redis list using the LLEN command in TypeScript. It first adds elements to a list using RPUSH and then retrieves the list's length, logging the result to the console. ```typescript await redis.rpush("key", "a", "b", "c"); const length = await redis.llen("key"); console.log(length); // 3 ``` -------------------------------- ### Upstash Redis XREVRANGE Command Examples (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the XREVRANGE command in Python to fetch stream entries. It covers fetching all entries in reverse order, limiting the count, and specifying a particular ID range. ```APIDOC ## XREVRANGE Command Examples (Python) ### Description Fetches stream entries in reverse order. Supports fetching all entries, limiting the count, and specifying ID ranges. ### Method `XREVRANGE` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Examples #### Fetch all entries in reverse order: ```python result = redis.xrevrange("mystream", "+", "-") ``` #### Fetch a limited number of entries in reverse order: ```python result = redis.xrevrange("mystream", "+", "-", count=2) ``` #### Fetch entries within a specific ID range in reverse order: ```python result = redis.xrevrange("mystream", end="1638360173533-2", start="1638360173533-0") ``` ### Response #### Success Response (200) - **result** (list) - A list of stream entries, where each entry is a dictionary containing the entry ID and its fields. ``` -------------------------------- ### RPUSH Command Example in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the RPUSH command to add elements to the end of a list in Upstash Redis. It shows the command's usage and verifies the list's state after the operation. This requires the 'redis' library. ```APIDOC ## RPUSH Command Example in Python ### Description Demonstrates how to use the RPUSH command to add elements to the end of a list in Upstash Redis. It shows the command's usage and verifies the list's state after the operation. This requires the 'redis' library. ### Method POST (Implicit for SDK calls) ### Endpoint (Not applicable for SDK method) ### Parameters (Not applicable for SDK method) ### Request Example ```python assert redis.rpush("mylist", "one", "two", "three") == 3 assert lrange("mylist", 0, -1) == ["one", "two", "three"] ``` ### Response (Not applicable for SDK method) ``` -------------------------------- ### Upstash Redis Transaction Example Response Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the expected JSON response structure for a transaction executed via Upstash Redis. It includes successful command results and an example of an error response when a command fails due to incorrect input type. ```APIDOC ## Upstash Redis Transaction Example Response ### Description Illustrates the expected JSON response structure for a transaction executed via Upstash Redis. It includes successful command results and an example of an error response when a command fails due to incorrect input type. ### Method POST (Implicit via Redis Client) ### Endpoint (Not Applicable - Client-side command execution) ### Parameters (Not Applicable) ### Request Example (Not Applicable - This describes a response format) ### Response #### Success Response - **Array of results** (Array) - Each object represents the result of a command in the transaction. - **result** (any) - The successful result of a command. - **error** (string) - An error message if a command failed. #### Response Example ```json [ { "result": "OK" }, { "result": "OK" }, { "error": "ERR value is not an int or out of range" }, { "result": 2 } ] ``` ``` -------------------------------- ### Install BullMQ and Upstash Redis Source: https://upstash.com/docs/redis/integrations/bullmq Installs the necessary packages for using BullMQ with Upstash Redis. This command-line instruction is a prerequisite for the subsequent code examples. ```bash npm install bullmq upstash-redis ``` -------------------------------- ### Setup Python Environment Source: https://upstash.com/docs/redis/quickstarts/vercel-python-runtime Commands to create and activate a Conda environment with Python 3.12 and install project dependencies. ```shell conda create --name vercel-django python=3.12 conda activate vercel-django pip install -r requirements.txt ``` -------------------------------- ### POST /redis/commands (Scoreboard) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using sorted sets in Upstash Redis to manage a scoreboard via React. ```APIDOC ## React Scoreboard with Upstash Redis ### Description Provides example functions for updating and retrieving scores in a scoreboard stored in Upstash Redis using ZADD and ZREVRANGE. ### Method POST ### Endpoint /redis/commands ### Parameters #### Request Body (for `updateScore`) - **command** (string) - Required - "zadd" - **key** (string) - Required - The scoreboard key - **members** (array) - Required - Array of objects with score and value ### Request Example ```javascript async function updateScore(playerName, score) { await redis.zadd('scoreboard', { score: score, value: playerName }); } ``` ### Response #### Success Response (200) - **data** (array) - An array of objects containing player names and scores. #### Response Example ```json [ {"value": "PlayerA", "score": 100}, {"value": "PlayerB", "score": 95} ] ``` ``` -------------------------------- ### Upstash Redis Transaction Example Response Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the expected JSON response structure for a transaction executed via Upstash Redis. It includes successful command results and an example of an error response when a command fails due to incorrect input type. ```json [ { "result": "OK" }, { "result": "OK" }, { "error": "ERR value is not an int or out of range" }, { "result": 2 } ] ``` -------------------------------- ### Initialize Serverless JavaScript Redis Client Source: https://upstash.com/docs/redis/overall/llms-txt Example of a serverless function handler in JavaScript for initializing a Redis client using the provided URL from environment variables. It demonstrates performing Redis operations and ensuring the connection is properly closed using `client.quit()` to manage concurrent connections. ```javascript 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" }; }; ``` -------------------------------- ### Job Processing and Event Queue with Serverless Redis Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates implementing job processing and event queues using Upstash Redis with AWS Lambda and Node.js. This example focuses on asynchronous task management. ```javascript import TagFilters from "../../src/components/Filter.js" Job Processing and Event Queue with Serverless Redis ``` -------------------------------- ### KEYS /api/redis/keys Source: https://upstash.com/docs/redis/overall/llms-txt Find all keys matching the given pattern. ```APIDOC ## KEYS /api/redis/keys ### Description Find all keys matching the given pattern. ### Method KEYS ### Endpoint /api/redis/keys ### Parameters #### Path Parameters - **pattern** (string) - Required - The pattern to match keys against (e.g., "user:*"). ### Request Example { "pattern": "user:*" } ### Response #### Success Response (200) - **keys** (string[]) - An array of keys matching the pattern. #### Response Example { "keys": ["user:1", "user:2"] } ``` -------------------------------- ### Initialize and Use Upstash Redis Client Source: https://upstash.com/docs/redis/howto/connectwithupstashredis Demonstrates how to initialize the Redis client using explicit credentials and perform a basic GET operation. This approach is suitable for environments where environment variables are managed manually. ```typescript 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); } })(); ``` -------------------------------- ### Manage List Elements with LPUSH and LRANGE in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates populating a Redis list using LPUSH and retrieving a subset of elements using LRANGE. ```typescript await redis.lpush("key", "a", "b", "c"); const elements = await redis.lrange("key", 1, 2); console.log(elements) // ["b", "c"] ``` -------------------------------- ### Install Toast Component for Notifications Source: https://upstash.com/docs/redis/overall/llms-txt Installs the 'react-toastify' npm package, which is used to display notification messages to the user in a user-friendly toast format. ```shell npm install --save react-toastify ``` -------------------------------- ### List MCP Servers via Claude CLI Source: https://upstash.com/docs/redis/overall/llms-txt A command to list all configured Model Context Protocol (MCP) servers in the Claude CLI environment, useful for verifying Upstash integration. ```bash claude mcp list ``` -------------------------------- ### Create Upstash Redis Instance using Fly CLI Source: https://upstash.com/docs/redis/overall/llms-txt Initiates the creation of an Upstash Redis database instance through the Fly CLI, guiding the user through configuration options. ```APIDOC ## Create Upstash Redis Instance using Fly CLI ### Description This command initiates the creation of an Upstash Redis database instance through the Fly CLI. It prompts the user to select an organization, choose a name for the database, set a primary region, and decide on memory eviction policies and plan. ### Method CLI Command ### Endpoint `flyctl redis create` ### Parameters None (interactive prompts) ### Request Example ```shell > flyctl redis create ? Select Organization: upstash (upstash) ? Choose a Redis database name (leave blank to generate one): ? Choose a primary region (can't be changed later) San Jose, California (US) (sjc) Upstash Redis can evict objects when memory is full. This is useful when caching in Redis. This setting can be changed later. Learn more at https://fly.io/docs/reference/redis/#memory-limits-and-object-eviction-policies ? Would you like to enable eviction? No ? Optionally, choose one or more replica regions (can be changed later): ? Select an Upstash Redis plan 3G: 3 GB Max Data Size Your Upstash Redis database silent-tree-6201 is ready. Apps in the upstash org can connect to at redis://default:978ba2e07tyrt67598acd8ac916a@fly-silent-tree-6201.upstash.io If you have redis-cli installed, use fly redis connect to connect to your database. ``` ### Response Output includes connection details for the newly created Redis instance. ``` -------------------------------- ### Retrieve Keys (Python SDK) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates fetching keys from Upstash Redis using the Python SDK's keys method. ```APIDOC ## Retrieve Keys with Upstash Redis Python SDK ### Description This example demonstrates fetching keys from Upstash Redis using the `redis.keys()` method in the Python SDK, showing how to retrieve keys matching a pattern or all keys. ### Method `redis.keys(pattern)` ### Endpoint Not applicable (SDK method) ### Parameters #### Query Parameters - **pattern** (string) - Required - The glob-style pattern to match keys against. ### Request Example ```python # Retrieve keys with a specific prefix keys = redis.keys("prefix*") # Retrieve all keys keys = redis.keys("*") ``` ### Response #### Success Response - **keys** (list[str]) - A list of keys matching the specified pattern. ``` -------------------------------- ### Create Serverless Project with CLI Source: https://upstash.com/docs/redis/overall/llms-txt Creates a new serverless project using the aws-java-maven template. This command initializes the project structure and configuration files. ```shell serverless create --template aws-java-maven --name counter-api -p aws-java-counter-api ``` -------------------------------- ### Handle Null Redis API Response Source: https://upstash.com/docs/redis/overall/llms-txt Example of the JSON structure returned by the Upstash REST API when a requested key or operation results in a null value. ```json { "result": null } ``` -------------------------------- ### Navigate into Phoenix Project Directory (Shell Command) Source: https://upstash.com/docs/redis/overall/llms-txt A shell command used to change the current working directory to a newly created Phoenix project folder, named `redix_demo` in this example. This is a common step after project generation. ```shell cd redix_demo ``` -------------------------------- ### Perform Key-Value and Set Operations in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Examples of using the Upstash Redis TypeScript SDK to set string values and manage set members. These snippets demonstrate basic key-value storage and retrieving set elements. ```typescript await redis.set("my-key", {my: "value"}); ``` ```typescript await redis.sadd("set", "a", "b", "c"); const members = await redis.smembers("set"); console.log(members); ``` -------------------------------- ### Build Leaderboard API with Cloudflare Workers and Redis Source: https://upstash.com/docs/redis/overall/llms-txt Details the creation of an edge leaderboard API using Cloudflare Workers and Upstash Redis. This example showcases real-time data handling at the network edge. ```javascript import TagFilters from "../../src/components/Filter.js" Build a Leaderboard API at Edge Using Cloudflare Workers and Redis ``` -------------------------------- ### Connect and Set Keys with Go Redis Client Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a connection to Upstash Redis using the go-redis library and performs a basic SET operation. Includes error handling for both the connection and the data operation. ```go package main import ( "fmt" "github.com/redis/go-redis/v9" "context" ) func main() { ctx := context.Background() r := redis.NewClient(&redis.Options{ Addr: "", Password: "", DB: 0, }) err := r.Set(ctx, "mykey", "Hello from Go!", 0).Err() if err != nil { panic(err) } val, err := r.Get(ctx, "mykey").Result() if err != nil { panic(err) } fmt.Println("mykey", val) } ``` -------------------------------- ### ZINTER: Aggregation with Scores (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to perform a ZINTER operation with aggregation and include scores in the result. This example uses the 'SUM' aggregation on two sets and returns the combined scores for common elements. ```APIDOC ## ZINTER: Aggregation with Scores (Python) ### Description Shows how to perform a ZINTER operation with aggregation and include scores in the result. This example uses the 'SUM' aggregation on two sets and returns the combined scores for common elements. ### Method `ZINTER` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters - **keys** (list[str]) - Required - A list of keys of the sorted sets to intersect. - **withscores** (bool) - Optional - Whether to include scores in the result. - **aggregate** (str) - Optional - The aggregation method (e.g., 'SUM', 'MIN', 'MAX'). ### Request Example ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zunion(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ``` ### Response #### Success Response (200) - **list[tuple[str, float]]** - A list of members and their aggregated scores. ``` -------------------------------- ### Connect and Use upstash-redis Client with Environment Variables (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Initializes the upstash-redis client by automatically loading credentials from environment variables (UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN). It then performs a GET operation to retrieve data. ```typescript 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); } })(); ``` -------------------------------- ### Get List Length via LLEN API Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the number of elements in a list stored at a specific key. If the key does not exist, the operation returns 0. ```http GET /llen?key=my_list ``` -------------------------------- ### POST /v1/redis/xread Source: https://upstash.com/docs/redis/overall/llms-txt Reads data from one or multiple streams, starting from the specified IDs. Supports options for limiting the number of messages and reading only new messages. ```APIDOC ## POST /v1/redis/xread ### Description Reads data from one or multiple streams, starting from the specified IDs. Use `$` to read only new messages added after the command is issued. ### Method POST ### Endpoint /v1/redis/xread ### Parameters #### Request Body - **streams** (Dict[str, str]) - Required - A dictionary mapping stream keys to their starting IDs. - **count** (int) - Optional - The maximum number of messages to return per stream. ### Request Example { "streams": {"mystream": "0-0"}, "count": 10 } ### Response #### Success Response (200) - **response** (List[List[Any]]) - Returns a list where each element represents a stream and contains the stream key and a list of messages (ID and field-value pairs). #### Response Example [ ["mystream", [ ["1638360173533-0", {"field1": "value1", "field2": "value2"}], ["1638360173533-1", {"field1": "value3", "field2": "value4"}] ]] ] ``` -------------------------------- ### HSETNX Command Example in Python Source: https://upstash.com/docs/redis/overall/llms-txt This Python code snippet demonstrates the usage of the HSETNX command with Upstash Redis. It shows how to set a field if it doesn't exist and verifies the behavior when the field already exists. This function requires a Redis client instance. ```APIDOC ## HSETNX Command Example in Python ### Description This Python code snippet demonstrates the usage of the HSETNX command with Upstash Redis. It shows how to set a field if it doesn't exist and verifies the behavior when the field already exists. This function requires a Redis client instance. ### Method SDK Method (Python) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **hash** (string) - Required - The name of the hash. - **field** (string) - Required - The field to set. - **value** (string) - Required - The value to set. ### Request Example ```python assert redis.hsetnx("myhash", "field1", "Hello") == True assert redis.hsetnx("myhash", "field1", "World") == False ``` ### Response #### Success Response (200) - **status** (boolean) - True if the field was set, False otherwise. #### Response Example ```json True ``` ``` -------------------------------- ### Create Serverless Project (Serverless CLI) Source: https://upstash.com/docs/redis/tutorials/serverless_java_redis Creates a new serverless project using the aws-java-maven template. This command initializes the project structure and configuration files. ```shell serverless create --template aws-java-maven --name counter-api -p aws-java-counter-api ``` -------------------------------- ### LRANGE Command Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves a range of elements from a list stored at a specified key. The range is defined by start and end indices, which can be negative to count from the end of the list. ```APIDOC ## LRANGE Command ### Description Returns the specified elements of the list stored at key. ### Method LRANGE ### Endpoint LRANGE ### Parameters #### Path Parameters - **key** (str) - Required - The key of the list. - **start** (int) - Required - The starting index of the range to return. Use negative numbers to specify offsets starting at the end of the list. - **end** (int) - Required - The ending index of the range to return. Use negative numbers to specify offsets starting at the end of the list. ### Response #### Success Response (200) - **elements** (Array) - An array containing the elements within the specified range. #### Response Example ```json ["element1", "element2", "element3"] ``` ``` -------------------------------- ### Upstash Ratelimit Plugin Configuration Source: https://upstash.com/docs/redis/overall/llms-txt Configuration parameters for the Upstash Ratelimit Strapi plugin. ```APIDOC ## Plugin Configuration ### Description Parameters to enable or disable the Upstash Ratelimit Strapi plugin. ### Parameters - **enabled** (boolean) - Default: true - Enable or disable the plugin. ### Configuration Example { "enabled": false } ``` -------------------------------- ### Install Ratelimit Package (npm) Source: https://upstash.com/docs/redis/overall/llms-txt Installs the Upstash Ratelimit library using npm. This package is essential for implementing rate limiting features in your application. ```bash npm install @upstash/ratelimit ``` -------------------------------- ### Create Serverless Project (Serverless CLI) Source: https://upstash.com/docs/redis/overall/llms-txt Creates a new serverless project using the aws-java-maven template. This command initializes the project structure and configuration files. ```APIDOC ## Create Serverless Project (Serverless CLI) ### Description Creates a new serverless project using the aws-java-maven template. This command initializes the project structure and configuration files. ### Method Shell Command ### Endpoint N/A ### Parameters None ### Request Example ```shell serverless create --template aws-java-maven --name counter-api -p aws-java-counter-api ``` ### Response #### Success Response (200) - **Output**: A new serverless project named `counter-api` is created in the `aws-java-counter-api` directory with the specified Java Maven template. ``` -------------------------------- ### Trim list with LTRIM Source: https://upstash.com/docs/redis/overall/llms-txt Trims a Redis list to a specific range of elements using the LTRIM command. Requires a key, start index, and stop index. ```python success = redis.ltrim('my_list', 0, 5) ``` -------------------------------- ### RPUSHX and LPUSH Example with Existing List (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using the RPUSHX command to push an element to the end of an existing list in Upstash Redis, following an initial LPUSH operation. It logs the final length of the list. Requires a Redis client instance. ```typescript await redis.lpush("key", "a", "b", "c"); const length = await redis.rpushx("key", "d"); console.log(length); // 4 ``` -------------------------------- ### Redis SDIFFSTORE Source: https://upstash.com/docs/redis/overall/llms-txt Writes the difference between sets to a new set. ```APIDOC ## Redis SDIFFSTORE ### Description Write the difference between sets to a new set. ### Method APICALL ### Endpoint /redis/sdiffstore ### Parameters #### Query Parameters - **destination** (str) - Required - The key of the set to store the resulting set in. - **keys** (List[str]) - Required - The keys of the sets to perform the difference operation on. ### Request Example ```json { "destination": "new_set_key", "keys": ["set1", "set2"] } ``` ### Response #### Success Response (200) - **Count** (int) - The number of elements in the resulting set. #### Response Example ```json 5 ``` ``` -------------------------------- ### Iterate Sorted Set Members with ZSCAN (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Provides a Python example for iterating through all members and scores of a Redis sorted set using the ZSCAN command. It demonstrates how to handle cursor-based pagination for retrieving all elements, optionally filtering by a match pattern. ```python import redis r = redis.Redis.from_url("redis://:@:") # Replace with your connection details cursor = 0 results = [] while True: cursor, keys = r.zscan("myzset", cursor, match="*") # Replace "myzset" with your key results.extend(keys) if cursor == 0: break for key, score in results: print(f"Member: {key.decode()}, Score: {score}") ``` -------------------------------- ### Retrieve Database Size via DBSIZE Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the total count of keys in the current database. The example demonstrates usage via a TypeScript Redis client. ```typescript const keys = await redis.dbsize(); console.log(keys); ``` -------------------------------- ### Redis TYPE Command Example in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `upstash-redis` client in TypeScript to set a key with a string value and then retrieve its data type using the `type` command. This is a client-side SDK method. ```typescript // Assuming 'redis' is an initialized Upstash Redis client instance // await redis.set('mykey', 'myvalue'); // const dataType = await redis.type('mykey'); // console.log(dataType); // Output: "string" ``` -------------------------------- ### Initialize Upstash Redis Client from Environment (Python) Source: https://upstash.com/docs/redis/sdks/py/gettingstarted Shows how to initialize Upstash Redis clients by automatically loading credentials from environment variables. Supports both synchronous and asynchronous clients. ```python # for sync use from upstash_redis import Redis redis = Redis.from_env() # for async use from upstash_redis.asyncio import Redis redis = Redis.from_env() ``` -------------------------------- ### Initialize Redis Data via CLI Source: https://upstash.com/docs/redis/howto/getstartedcloudflareworkers Commands to populate the Redis database with location-specific greeting messages using the redis-cli. ```shell set GB "Ey up?" set US "Yo, what’s up?" set TR "Naber dostum?" set DE "Was ist los?" ``` -------------------------------- ### Create Next.js App and Initialize SST Source: https://upstash.com/docs/redis/quickstarts/ion These commands set up a new Next.js project and initialize the Serverless Stack (SST) framework within it. SST simplifies the deployment and management of serverless applications on AWS. ```shell npx create-next-app@latest cd my-app sst init ``` -------------------------------- ### Basic Write and Read Operations (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates basic set and get operations using the Upstash Redis TypeScript SDK. This function writes a random key-value pair and returns the key. It initializes a Redis client from environment variables. ```typescript import { Redis } from "@upstash/redis"; import { nanoid } from "nanoid"; 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; }; ``` -------------------------------- ### Execute Lua Script with EVAL_RO (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates using the `eval_ro` command in Python to execute a read-only Lua script. This example shows how to return an argument passed to the script using the `args` parameter. ```python assert redis.eval_ro("return ARGV[1]", args=["Hello"]) == "Hello" ``` -------------------------------- ### Get All Hash Values in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates setting multiple fields in a Redis hash and retrieving all stored values using the hvals command. ```typescript await redis.hset("key", { field1: "Hello", field2: "World", }) const values = await redis.hvals("key") console.log(values) // ["Hello", "World"] ``` -------------------------------- ### Get Set Cardinality with SCARD (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates retrieving the number of members in a Redis set using the SCARD command in TypeScript. It first adds members to a set using SADD and then uses SCARD to get the set's cardinality, logging the result. ```typescript await redis.sadd("key", "a", "b", "c"); const cardinality = await redis.scard("key"); console.log(cardinality); // 3 ``` -------------------------------- ### Get Value from Redis using Python Source: https://upstash.com/docs/redis/sdks/py/commands/string/get Demonstrates how to retrieve a value from Redis using the GET command in Python. It first sets a key-value pair and then fetches the value to verify its correctness. This requires the 'redis' library to be installed. ```python redis.set("key", "value") assert redis.get("key") == "value" ``` -------------------------------- ### Initialize Serverless Framework Project Source: https://upstash.com/docs/redis/tutorials/rate-limiting Commands to scaffold a new Serverless Framework project using the AWS Node.js HTTP API template. ```shell serverless cd ratelimit-serverless ``` -------------------------------- ### Get Multiple Random Fields from Hash (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to retrieve multiple random fields from a Redis hash using the HRANDFIELD command with the 'count' argument in Python. ```APIDOC ## Get Multiple Random Fields from Hash ### Description Retrieves multiple random fields from a Redis hash using the HRANDFIELD command. ### Method N/A (SDK Usage) ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters - **key** (string) - Required - The key of the hash. - **count** (integer) - Optional - The number of random fields to return. ### Request Example ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) random_fields = redis.hrandfield("myhash", count=2) ``` ### Response #### Success Response (200) - **fields** (array) - An array of random field-value pairs from the hash. #### Response Example ```json ["field1", "field2"] ``` ``` -------------------------------- ### Run Django Development Server (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Starts the local Django development server. This command is used to test Redis-backed functionalities in a Django application. ```shell python manage.py runserver ``` -------------------------------- ### Deploy SST Application Source: https://upstash.com/docs/redis/overall/llms-txt Commands to run an SST application locally and deploy it to a production environment with required secrets. ```shell npm run dev cd packages/web npm run dev npx sst secrets set --stage prod UPSTASH_REDIS_REST_URL npx sst secrets set --stage prod UPSTASH_REDIS_REST_TOKEN npx sst deploy --stage prod ``` -------------------------------- ### HEXPIRETIME Usage Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `hexpiretime` command with Upstash Redis in a TypeScript application, including setting a key, expiring a field, and retrieving its expiration time. ```APIDOC ## HEXPIRETIME ### Description Retrieves the expiration time of a field in a hash. ### Method N/A (Redis Command) ### Endpoint N/A (Redis Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' is an initialized Upstash Redis client await redis.hset("my-key", "my-field", "my-value"); await redis.hexpireat("my-key", "my-field", Math.floor(Date.now() / 1000) + 10); const expireTime = await redis.hexpiretime("my-key", "my-field"); console.log(expireTime); // e.g., [1697059200] ``` ### Response #### Success Response (200) - **expireTime** (number | null) - The expiration time in seconds, or null if the field does not exist or has no expiration. #### Response Example ```json 1697059200 ``` ``` -------------------------------- ### Initialize Koyeb App with Upstash Redis (CLI) Source: https://upstash.com/docs/redis/quickstarts/koyeb Initializes a new Koyeb application from a GitHub repository, configuring environment variables for Upstash Redis. Requires replacing placeholders with actual GitHub and Upstash credentials. ```bash koyeb app init example-koyeb-upstash \ --git github.com// \ --git-branch main \ --ports 3000:http \ --routes /:3000 \ --env PORT=3000 \ --env UPSTASH_REDIS_REST_URL="" \ --env UPSTASH_REDIS_REST_TOKEN="" ``` -------------------------------- ### Perform ZUNIONSTORE operations in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates merging multiple sorted sets into a new sorted set using Upstash Redis. Examples cover basic union, applying weights to input sets, and using aggregation methods like 'sum'. ```typescript 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"]); console.log(res) // 2 ``` ```typescript 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 ``` ```typescript 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 ``` -------------------------------- ### SDIFF Command Source: https://upstash.com/docs/redis/overall/llms-txt Returns the difference between multiple sets. ```APIDOC ## SDIFF Command ### Description Returns the difference between multiple sets. The resulting set contains elements that are in the first set but not in any of the other sets. ### Method `redis.sdiff(set1, set2, ...)` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```python redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); assert redis.sdiff("set1", "set2") == {"a", "b"} ``` ### Response #### Success Response (200) - **Set**: A set containing the difference between the specified sets. #### Response Example ```json ["a", "b"] ``` ``` -------------------------------- ### Execute Custom Redis Commands via API Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to execute arbitrary Redis commands not explicitly supported by the SDK by sending a POST request with the command and arguments as an array. ```json { "command": ["XLEN", "test_stream"] } ``` -------------------------------- ### Create Laravel Project with Composer Source: https://upstash.com/docs/redis/quickstarts/laravel Creates a new Laravel project named 'example-app' using Composer, an alternative method if the Laravel CLI is not installed globally. It then navigates into the project directory. ```shell composer create-project laravel/laravel example-app cd example-app ``` -------------------------------- ### POST /api/settings/ratelimit Source: https://upstash.com/docs/redis/overall/llms-txt Configures different rate limiting algorithms for specific API routes. ```APIDOC ## POST /api/settings/ratelimit ### Description Configures different rate limiting algorithms for specific API routes within a Strapi application using the `strapi-plugin-upstash-ratelimit`. ### Method POST ### Endpoint /api/settings/ratelimit ### Parameters #### Request Body - **strapi-plugin-upstash-ratelimit** (object) - Required - Plugin configuration. - **enabled** (boolean) - Required - Whether the plugin is enabled. - **config** (object) - Required - Plugin configuration details. - **token** (string) - Required - Upstash Redis authentication token. - **url** (string) - Required - Upstash Redis URL. - **strategy** (array) - Required - Array of rate limiting strategies. - **algorithm** (string) - Required - The rate limiting algorithm (e.g., `fixed-window`, `tokenBucket`). - **tokens** (number) - Required - The maximum number of tokens allowed. - **window** (string) - Required - The time window for the rate limit. ### Response #### Success Response (200) - **status** (string) - Configuration update status. ``` -------------------------------- ### Configure Rate Limits for API Routes (JSON) Source: https://upstash.com/docs/redis/overall/llms-txt Example JSON configuration for the `strapi-plugin-upstash-ratelimit` to set different rate limiting strategies for specific API routes. It allows defining algorithms like fixed-window or tokenBucket for distinct paths and methods. ```json { "enabled": true, "resolve": "./node_modules/strapi-plugin-upstash-ratelimit/strapi-plugin-upstash-ratelimit.js", "config": { "enabled": true, "token": "YOUR_UPSTASH_TOKEN", "url": "YOUR_UPSTASH_URL", "strategy": [ { "methods": ["POST"], "path": "/api/settings/ratelimit", "identifierSource": "header:x-forwarded-for", "limiter": { "algorithm": "fixed-window", "tokens": 100, "window": "1m" } }, { "methods": ["GET"], "path": "/api/users", "identifierSource": "header:authorization", "limiter": { "algorithm": "tokenBucket", "tokens": 50, "window": "1h", "refillRate": 10 } } ], "prefix": "ratelimit:" } } ``` -------------------------------- ### Initialize Upstash Redis Client in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Configures the Upstash Redis client using a REST URL and token. Shows an asynchronous GET operation with error handling. ```typescript 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); } })(); ``` -------------------------------- ### Install Node.js Dependencies for Upstash Source: https://upstash.com/docs/redis/overall/llms-txt Installs the required npm packages for interacting with Upstash Redis and building web applications. ```bash npm install @upstash/redis express ``` -------------------------------- ### SCAN /api/redis/scan Source: https://upstash.com/docs/redis/overall/llms-txt Incrementally iterate the keys space. ```APIDOC ## SCAN /api/redis/scan ### Description Incrementally iterate the keys space. ### Method SCAN ### Endpoint /api/redis/scan ### Parameters #### Path Parameters - **cursor** (string) - Required - The cursor returned by the last call to SCAN, or 0 to start. - **pattern** (string) - Optional - The pattern to match keys against. - **count** (integer) - Optional - The number of elements to return per page. ``` -------------------------------- ### LPUSH Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the LPUSH command in Upstash Redis with TypeScript. This command pushes one or more values onto the head of a list. It returns the new length of the list after the push operation. ```APIDOC ## LPUSH Command Example (TypeScript) ### Description This example demonstrates how to use the LPUSH command in Upstash Redis with TypeScript. This command pushes one or more values onto the head of a list. It returns the new length of the list after the push operation. ### Method SDK Method (TypeScript) ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **key** (string) - Required - The key of the list. - **value** (*string) - Required - One or more values to insert. ### Request Example ```typescript const length1 = await redis.lpush("key", "a", "b", "c"); console.log(length1); // 3 const length2 = await redis.lpush("key", "d"); console.log(length2); // 4 ``` ### Response #### Success Response (200) - **type** (integer) - The length of the list after the push operation. #### Response Example ```json 4 ``` ``` -------------------------------- ### LRANGE Redis Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Provides API documentation for the LRANGE Redis command, which retrieves a range of elements from a list. It specifies the required key, start, and end indices, and the expected array response. ```APIDOC ## LRANGE Redis Command API Documentation ### Description Returns the specified elements of the list stored at key. ### Method N/A (Command documentation) ### Endpoint N/A ### Parameters #### Arguments - **key** (string) - Required - The key of the list. - **start** (integer) - Required - The starting index of the range to return. Use negative numbers to specify offsets starting at the end of the list. - **end** (integer) - Required - The ending index of the range to return. Use negative numbers to specify offsets starting at the end of the list. ### Response #### Success Response - **TValue[]** (array) - Required - The list of elements in the specified range. ``` -------------------------------- ### GET Command (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the value associated with a specified key from Upstash Redis. If the key does not exist, it returns None. This function requires a Redis client instance. ```APIDOC ## GET Command (Python) ### Description Retrieves the value associated with a specified key from Upstash Redis. If the key does not exist, it returns None. ### Method Client Method Call ### Endpoint N/A (Command executed via client) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'redis' is an initialized Upstash Redis client redis.set("key", "value") assert redis.get("key") == "value" ``` ### Response #### Success Response (200) - **value** (string) - The value associated with the key, or None if the key does not exist. ``` -------------------------------- ### Run Flask Application (Shell) Source: https://upstash.com/docs/redis/overall/llms-txt Executes the Flask application locally. This command starts the development server, typically accessible at http://127.0.0.1:5000/. ```shell python app.py ``` -------------------------------- ### RENAME /api/redis/rename Source: https://upstash.com/docs/redis/overall/llms-txt Rename a key. ```APIDOC ## RENAME /api/redis/rename ### Description Rename a key. ### Method RENAME ### Endpoint /api/redis/rename ### Parameters #### Path Parameters - **oldKey** (string) - Required - The current name of the key. - **newKey** (string) - Required - The new name for the key. ### Request Example { "oldKey": "mykey", "newKey": "newkey" } ### Response #### Success Response (200) - **success** (boolean) - True if the key was renamed successfully. #### Response Example { "success": true } ``` -------------------------------- ### Retrieve Keys from Upstash Redis (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `redis.keys()` method in Python to fetch keys from Upstash Redis. Examples include matching keys by a specific prefix and retrieving all keys. Be cautious when using `keys('*')` in production environments as it can impact performance on large datasets. ```python import redis # Assuming 'redis' is an initialized Upstash Redis client instance # Retrieve keys with a specific prefix keys_with_prefix = redis.keys("prefix*") print(f"Keys with prefix 'prefix*': {keys_with_prefix}") # Retrieve all keys (use with caution on large datasets) all_keys = redis.keys("*") print(f"All keys: {all_keys}") ``` -------------------------------- ### TypeScript LPOP Command Examples for Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using the LPOP command in TypeScript to remove and return elements from a list in Upstash Redis. Shows popping a single element and multiple elements, along with their expected output. ```APIDOC ## TypeScript LPOP Command Examples for Upstash Redis ### Description Demonstrates using the LPOP command in TypeScript to remove and return elements from a list in Upstash Redis. Shows popping a single element and multiple elements, along with their expected output. ### Method POST ### Endpoint (Assumed Upstash Redis endpoint) ### Parameters * **key** (string) - Required - The key of the list. * **count** (integer) - Optional - The number of elements to pop. If not provided, defaults to 1. ### Request Example 1: Pop a single element ```typescript await redis.rpush("key", "a", "b", "c"); const element = await redis.lpop("key"); console.log(element); // "a" ``` ### Request Example 2: Pop multiple elements ```typescript await redis.rpush("key", "a", "b", "c"); const element = await redis.lpop("key", 2); console.log(element); // ["a", "b"] ``` ### Response #### Success Response - **element(s)** (string or array of strings) - The element(s) removed from the list. ``` -------------------------------- ### Retrieve Latency Histogram via cURL Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves performance metrics by sending a GET request to the latency histogram endpoint. This is useful for monitoring and analyzing test performance. ```shell curl https://v7xx4aa2ib.execute-api.us-east-1.amazonaws.com/get?name=perf-test-1 ``` -------------------------------- ### Initialize Fixed Window Ratelimit with Upstash Redis (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates setting up a fixed window rate limiter using the `upstash_ratelimit` library with Upstash Redis in Python. It configures a limit of 10 requests per 10-second window and provides a conceptual example of how to use the `take` method. ```python from upstash_ratelimit import Ratelimit, FixedWindow from upstash_redis import Redis ratelimit = Ratelimit( redis=Redis.from_env(), limiter=FixedWindow(max_requests=10, window=10), ) # Example usage: # success, remaining_time = ratelimit.take("user_id_123") ``` -------------------------------- ### TypeScript LPOP Command Examples for Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates using the LPOP command in TypeScript to remove and return elements from a list in Upstash Redis. Shows popping a single element and multiple elements, along with their expected output. ```typescript import { Redis } from '@upstash/redis'; const redis = new Redis({ url: process.env.UPSTASH_REDIS_URL, token: process.env.UPSTASH_REDIS_TOKEN, }); async function popSingleElement() { try { await redis.rpush("key", "a", "b", "c"); console.log("Pushed 'a', 'b', 'c' to list 'key'."); const element = await redis.lpop("key"); console.log(`Popped single element: ${element}`); // "a" } catch (error) { console.error("Error popping single element:", error); } } popSingleElement(); ``` ```typescript import { Redis } from '@upstash/redis'; const redis = new Redis({ url: process.env.UPSTASH_REDIS_URL, token: process.env.UPSTASH_REDIS_TOKEN, }); async function popMultipleElements() { try { await redis.rpush("key", "a", "b", "c"); console.log("Pushed 'a', 'b', 'c' to list 'key'."); const elements = await redis.lpop("key", 2); console.log(`Popped multiple elements: ${JSON.stringify(elements)}`); // ["a", "b"] } catch (error) { console.error("Error popping multiple elements:", error); } } popMultipleElements(); ``` -------------------------------- ### Get Length of Redis List (LLEN) Source: https://upstash.com/docs/redis/overall/llms-txt This APIDOC specifies the LLEN command for Redis lists. It takes a key as a string argument and returns the number of elements in the list at that key. ```APIDOC ## LLEN Command ### Description Returns the number of elements in the list stored at the specified key. ### Method LLEN ### Endpoint Not applicable (command-based) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Arguments - **key** (string) - Required - The key of the list. ### Response #### Success Response (200) - **result** (number) - The length of the list at the key. ``` -------------------------------- ### Configure Django URL routing Source: https://upstash.com/docs/redis/quickstarts/django Maps the root URL path to the index view function within the Django project configuration. ```python from django.urls import path from myapp import views urlpatterns = [ path('', views.index), ] ``` -------------------------------- ### JSON Response for Redis Command Error Source: https://upstash.com/docs/redis/overall/llms-txt Examples of JSON responses from the Upstash REST API when a Redis command fails or is rejected, showing the `error` field with an explanatory message. ```APIDOC ## JSON Response for Redis Command Error ### Description Examples of JSON responses from the Upstash REST API when a Redis command fails or is rejected, showing the `error` field with an explanatory message. ### Method REST API Response ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Error Response - **error** (string) - An explanatory message detailing the reason for the command failure. #### Response Example ```json {"error":"WRONGPASS invalid password"} {"error":"ERR wrong number of arguments for 'get' command"} ``` ``` -------------------------------- ### Redis Pipeline Example in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use the pipeline feature in Upstash Redis with TypeScript. Pipelining allows sending multiple commands in a single HTTP request for efficiency, though execution is not atomic. It takes a Redis client instance and returns an array of command responses. ```typescript 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]>(); ``` -------------------------------- ### Handle Asynchronous Background Tasks in Serverless Environments Source: https://upstash.com/docs/redis/sdks/ratelimit-ts/gettingstarted Ensures that background operations like MultiRegion synchronization or analytics reporting complete before the serverless runtime terminates. It utilizes the 'pending' promise returned by the limit method and the platform's 'waitUntil' context method. ```typescript const { pending } = await ratelimit.limit("id"); context.waitUntil(pending); ``` -------------------------------- ### Get Hash Field Length with HSTRLEN Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the length of the string value associated with a specific field in a Redis hash. Requires the key and field name as input parameters. ```python redis.hstrlen("key", "field") ``` -------------------------------- ### Use HRANDFIELD Command with Upstash Redis (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates TypeScript examples for the `hrandfield` command, demonstrating how to retrieve random fields, multiple random fields, and random fields with their values from a Redis hash. This requires the @upstash/redis SDK. ```typescript 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" ``` ```typescript 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 ``` ```typescript await redis.hset("key", { id: 1, username: "chronark", name: "andreas", }); const randomFields = await redis.hrandfield("key", 2, true); console.log(randomFields); // { id: "1", username: "chronark" } or any other combination ``` -------------------------------- ### Navigate into the newly created Phoenix project directory Source: https://upstash.com/docs/redis/overall/llms-txt Changes the current working directory to the specified project folder. ```APIDOC ## Navigate into the newly created Phoenix project directory ### Description Changes the current working directory to the specified project folder. ### Method Shell Command ### Endpoint N/A ### Parameters - **project_directory** (string) - The name of the project directory to navigate into. ### Request Example ```bash cd redix_demo ``` ### Response N/A (Changes the current directory) ``` -------------------------------- ### Basic Upstash Redis Operations in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates fundamental operations with the Upstash Redis client in TypeScript, including setting and getting string values, and using sorted sets, lists, hashes, and sets. Requires UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN environment variables. ```typescript 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) ``` -------------------------------- ### Create Redis Search Index Source: https://upstash.com/docs/redis/search/getting-started This snippet shows how to create a Redis Search index for JSON data. It defines the index name, data type, prefix, and schema with various field types. Dependencies include the Upstash Redis client library for each language. ```TypeScript import { Redis, s } from "@upstash/redis"; const redis = Redis.fromEnv(); const index = await redis.search.createIndex({ name: "products", dataType: "json", prefix: "product:", schema: s.object({ name: s.string(), description: s.string(), category: s.string().noTokenize(), price: s.number(), inStock: s.boolean(), }), }); ``` ```Python from upstash_redis import Redis redis = Redis.from_env() index = redis.search.create_index( name="products", data_type="json", prefix="product:", schema={ "name": "TEXT", "description": "TEXT", "category": {"type": "TEXT", "notokenize": True}, "price": "F64", "inStock": "BOOL", }, ) ``` ```Redis CLI SEARCH.CREATE products ON JSON PREFIX 1 product: SCHEMA name TEXT description TEXT category TEXT NOTOKENIZE price F64 FAST inStock BOOL ``` -------------------------------- ### Install Upstash Redis SDK for Node.js Source: https://upstash.com/docs/redis/overall/llms-txt Installs the official Upstash Redis client library for Node.js using npm. This package is required for Cloudflare Workers to interact with an Upstash Redis database via its REST API. ```bash cd greetings-cloudflare npm install @upstash/redis ``` -------------------------------- ### Deploy AWS SAM Application Source: https://upstash.com/docs/redis/overall/llms-txt Deploys an AWS SAM (Serverless Application Model) application to AWS. The `--guided` flag initiates an interactive deployment process, prompting for necessary configuration details, including environment variables for Upstash Redis. ```shell sam deploy --guided ``` -------------------------------- ### Fetch Weather Data and Cache in Redis (Elixir) Source: https://upstash.com/docs/redis/overall/llms-txt An Elixir example demonstrating how to fetch weather data from an external API, process it, and cache the response in Redis for 8 hours. This reduces redundant API calls. It uses an environment variable for the API key. ```elixir defmodule Weather do @api_url "http://api.weatherapi.com/v1/current.json" @cache_ttl 60 * 60 * 8 # 8 hours def fetch_weather_from_api(location) do cache_key = "weather:#{location}" case Cache.get(cache_key) do {:ok, cached_data} -> {:ok, cached_data} _ -> with {:ok, api_key} <- System.fetch_env("WEATHER_API_KEY"), {:ok, response} <- fetch_from_external_api(location, api_key), {:ok, processed_data} <- process_api_response(response) do Cache.put(cache_key, processed_data, @cache_ttl) {:ok, processed_data} else error -> error end end end defp fetch_from_external_api(location, api_key) do HTTPoison.get!(@api_url, ["key": api_key], query: [q: location]) |> handle_response end defp handle_response(%HTTPoison.Response{body: body, status_code: 200}) do {:ok, Jason.decode!(body)} end defp handle_response(%HTTPoison.Response{body: body}) do {:error, Jason.decode!(body)} end defp process_api_response(data) do # Placeholder for actual data processing {:ok, data} end # Mock Cache module for demonstration defmodule Cache do @cache MapSet.new() def get(key), do: Map.get(@cache, key) def put(key, value, _ttl), do: Map.put(@cache, key, value) end end # Example usage: # Weather.fetch_weather_from_api("London") ``` -------------------------------- ### Redis ZINTER Command Examples (Python) Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zinter Demonstrates how to use the ZINTER command in Python to find the intersection of sets. Includes examples for basic intersection, aggregation with scores, and weighted intersections. ```python 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"] ``` ```python 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)] ``` ```python 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)] ``` -------------------------------- ### Retrieve Pending Messages with XPENDING in Python Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xpending Demonstrates how to use the XPENDING command to fetch pending message information from a Redis stream. The examples cover basic summary retrieval, range-based queries, and filtered queries using consumer and idle time parameters. ```python result = redis.xpending("mystream", "mygroup") ``` ```python result = redis.xpending("mystream", "mygroup", start="-", end="+", count=10) ``` ```python result = redis.xpending("mystream", "mygroup", start="-", end="+", count=5, consumer="consumer1", idle=10000) ``` -------------------------------- ### Setup ioredis and @upstash/search-ioredis client Source: https://upstash.com/docs/redis/search/adapters/ioredis Initialize an ioredis client using your Upstash Redis connection string and then create a search client using the @upstash/search-ioredis adapter. The adapter wraps your existing ioredis instance. ```typescript import IORedis from "ioredis"; import { createSearch, s } from "@upstash/search-ioredis"; // Create ioredis client using your Upstash Redis URL const ioredis = new IORedis(process.env.REDIS_URL); // Create search client const search = createSearch(ioredis); ``` -------------------------------- ### Basic Redis Commands via REST API Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to execute fundamental Redis commands like GET, SET, MGET, HGET, and ZADD using simple HTTP GET and POST requests to the Upstash Redis REST API. Authentication is handled via a Bearer token. ```APIDOC ## Basic Redis Commands via REST API ### Description Demonstrates how to execute fundamental Redis commands like GET, SET, MGET, HGET, and ZADD using simple HTTP GET and POST requests to the Upstash Redis REST API. Authentication is handled via a Bearer token. ### Method GET, POST ### Endpoint `https://.upstash.io//[arguments...]` ### Parameters #### Query Parameters None #### Request Body None (for GET requests) ### Request Example ```bash # GET command example curl https://us1-merry-cat-32748.upstash.io/get/foo \ -H "Authorization: Bearer " # POST SET command example curl https://us1-merry-cat-32748.upstash.io/set/foo/bar \ -H "Authorization: Bearer " # POST SET with expiration example curl https://us1-merry-cat-32748.upstash.io/set/key/value/EX/100 \ -H "Authorization: Bearer " # GET MGET command example curl https://us1-merry-cat-32748.upstash.io/mget/key1/key2/key3 \ -H "Authorization: Bearer " # GET HGET command example curl https://us1-merry-cat-32748.upstash.io/hget/employee:23381/salary \ -H "Authorization: Bearer " # POST ZADD command example (structure not fully defined in source, showing typical usage) # curl https://.upstash.io/zadd/////... \ # -H "Authorization: Bearer " ``` ### Response #### Success Response (200) - **response** (any) - The result of the Redis command. ``` -------------------------------- ### Initialize AWS CDK Project Directory Source: https://upstash.com/docs/redis/overall/llms-txt Creates a new directory for an AWS CDK project and changes the current directory to it. ```APIDOC ## Initialize AWS CDK Project Directory ### Description Creates a new directory for an AWS CDK project and changes the current directory to it. ### Method Shell command ### Endpoint Not applicable ### Parameters None ### Request Example ```shell mkdir counter-cdk && cd counter-cdk ``` ### Response #### Success Response (0) Shell returns exit code 0 upon successful execution. ``` -------------------------------- ### Install Django and Upstash Redis (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary Python packages for Django and the Upstash Redis client using pip. This prepares a Django project to use Upstash Redis. ```shell pip install django pip install upstash-redis ``` -------------------------------- ### Create React App for Notification API Source: https://upstash.com/docs/redis/overall/llms-txt This command initializes a new React application using create-react-app. This application will serve as the frontend for the serverless notification system. ```APIDOC ## Create React App for Notification API ### Description Initializes a new React project using `create-react-app` to serve as the frontend for a serverless notification system. ### Command ```bash npx create-react-app serverless-notification-api ``` ### Parameters - **serverless-notification-api**: The name of the new React application directory. ``` -------------------------------- ### POST /redis/commands (MGET) Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the values associated with multiple keys from Redis. ```APIDOC ## POST /redis/commands ### Description Retrieves the values associated with multiple keys from Redis. ### Method POST ### Endpoint /redis/commands ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **command** (string) - Required - "mget" - **keys** (array) - Required - List of keys to retrieve ### Request Example ```typescript const values = await redis.mget("key1", "key2", "key3"); ``` ### Response #### Success Response (200) - **Array**: An array containing the values of the requested keys. If a key does not exist, its corresponding value will be `null`. #### Response Example ```json ["value1", null, "value3"] ``` ``` -------------------------------- ### Dockerfile for Node.js Application Source: https://upstash.com/docs/redis/tutorials/cloud_run_sessions This Dockerfile defines the steps to build a container image for a Node.js application. It copies package files, installs dependencies, copies the application code, and sets the command to start the service. ```dockerfile COPY package*.json ./ RUN npm install COPY . ./ CMD [ "npm", "start" ] ``` -------------------------------- ### Get Hash Field Count with HLEN Source: https://upstash.com/docs/redis/sdks/py/commands/hash/hlen Demonstrates how to use the HLEN command to count fields in a Redis hash. The example shows initializing a hash with multiple fields and verifying the count using the Python Redis client. ```python assert redis.hlen("myhash") == 0 redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hlen("myhash") == 2 ``` -------------------------------- ### Connect with jedis (Java) Source: https://upstash.com/docs/redis/overall/llms-txt Connects to Upstash Redis using the jedis library for Java. It requires the endpoint, port, and password, with SSL enabled by default. The example shows setting and getting a key. ```java 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); ``` -------------------------------- ### Add data to Redis Stream using XADD (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to add data to a Redis stream using the `xadd` command in TypeScript. It includes an example of setting a maximum length for the stream using the `trim` option. Requires an Upstash Redis client. ```typescript await redis.xadd(key, "*", { name: "John Doe", age: 30 }, { trim: { type: "MAXLEN", threshold: 1000, comparison: "=", }, }); ``` -------------------------------- ### Install Upstash Rate Limiter via Pip Source: https://upstash.com/docs/redis/overall/llms-txt Installs the upstash-ratelimit Python package. This is the prerequisite for integrating rate limiting features into Python applications. ```bash pip install upstash-ratelimit ``` -------------------------------- ### GETBIT Command (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the `getbit` method with a Redis client in Python to retrieve a single bit at a specific offset from a given key. ```APIDOC ## GETBIT Command (Python) ### Description Retrieves a single bit at a specific offset from a given key. ### Method Client Method Call ### Endpoint N/A (Command executed via client) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'redis' is an initialized Upstash Redis client bit = redis.getbit(key, 4) ``` ### Response #### Success Response (200) - **bit** (integer) - The bit value (0 or 1) at the specified offset. ``` -------------------------------- ### Remove Elements from Redis List (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the RPOP command to remove and return elements from the right side of a list. Includes examples for popping a single element and multiple elements. ```typescript await redis.rpush("key", "a", "b", "c"); const element = await redis.rpop("key"); console.log(element); // "c" ``` ```typescript await redis.rpush("key", "a", "b", "c"); const element = await redis.rpop("key", 2); console.log(element); // ["c", "b"] ``` -------------------------------- ### XRANGE Command Usage (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `xrange` method with a TypeScript Redis client, showing the basic invocation with start and end IDs, and the expected console output format of the stream entries. This command retrieves a range of elements from a Redis stream. ```javascript redis.xrange(key, "-", "+"); ``` -------------------------------- ### Retrieve Keyspace Notification Configuration Source: https://upstash.com/docs/redis/overall/llms-txt Executes a CONFIG GET command to check the current settings for Redis keyspace notifications. Returns a list containing the configuration key and its active value. ```json ["CONFIG", "GET", "notify-keyspace-events"] ``` -------------------------------- ### Fetch Weather Data from Redis Cache in Elixir Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves cached weather data using the GET command. It decodes the JSON response and handles missing keys or retrieval errors. ```elixir 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 ``` -------------------------------- ### Create Serverless Project with Serverless Framework Source: https://upstash.com/docs/redis/tutorials/job_processing This snippet shows the command to initiate a new AWS Node.js serverless project using the Serverless Framework. It guides the user through the project creation process. ```shell ➜ 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. ``` -------------------------------- ### Get Random Field from Hash (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the HRANDFIELD command in Python to fetch a single random field from a Redis hash. Assumes a Redis client instance is available. ```APIDOC ## Get Random Field from Hash (Python) ### Description Demonstrates how to use the HRANDFIELD command in Python to fetch a single random field from a Redis hash. Assumes a Redis client instance is available. ### Method SDK Method ### Endpoint N/A (SDK Method) ### Parameters #### Query Parameters - **key** (string) - Required - The key of the hash. ### Request Example ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hrandfield("myhash") in ["field1", "field2"] ``` ### Response #### Success Response (200) - **field** (string) - A random field from the hash. ``` -------------------------------- ### Setup ioredis and @upstash/search-ioredis client (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Initializes an ioredis client with Upstash Redis connection string and creates a search client using the @upstash/search-ioredis adapter. Requires the REDIS_URL environment variable. ```typescript import IORedis from "ioredis"; import { createSearch, s } from "@upstash/search-ioredis"; // Create ioredis client using your Upstash Redis URL const ioredis = new IORedis(process.env.REDIS_URL); // Create search client const search = createSearch(ioredis); ``` -------------------------------- ### Configure Upstash MCP via Claude CLI Source: https://upstash.com/docs/redis/overall/llms-txt Commands to register the Upstash MCP server using the Claude CLI. These commands handle installation via npx and support both global and project-specific scopes. ```APIDOC ## Configure Upstash MCP via Claude CLI ### Description Commands for managing the Upstash MCP server using the Claude CLI, including adding and listing configurations for global or project scopes. ### Method Command Line Interface (CLI) ### Endpoint N/A (CLI commands) ### Parameters #### `claude mcp add upstash` Parameters - **--scope** (string) - Optional - Specifies the scope ('global' or 'project'). Defaults to global if not provided. - **--email** (string) - Required - Your Upstash account email. - **--api-key** (string) - Required - Your Upstash API key. ### Request Example (Add global MCP server) ```bash claude mcp add upstash -- npx -y @upstash/mcp-server@latest \ --email \ --api-key ``` ### Request Example (Add project-scoped MCP server) ```bash claude mcp add upstash --scope project -- npx -y @upstash/mcp-server@latest \ --email \ --api-key ``` ### Request Example (List MCP servers) ```bash claude mcp list ``` ### Response #### Success Response (add) - Output indicating successful registration of the MCP server. #### Success Response (list) - A list of configured MCP servers and their scopes. ``` -------------------------------- ### Execute BITCOUNT Command in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the BITCOUNT command to count set bits in a binary string. Shows both range-based and full-string counting using the execute_command method. ```python # Assuming 'redis' is an Upstash Redis client instance # Set some bits redis.setbit("mykey", 7, 1) redis.setbit("mykey", 8, 1) redis.setbit("mykey", 9, 1) # Count bits within a range (bytes 0 to 10) response_with_range = redis.execute_command("BITCOUNT", "mykey", 0, 10) print(response_with_range) # Output: 3 # Count all bits in the string response_without_range = redis.execute_command("BITCOUNT", "mykey") print(response_without_range) # Output: 3 ``` -------------------------------- ### HP TTL Python Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates setting a hash field with a millisecond expiration and retrieving its TTL using the hpttl command in Python. It utilizes the HSET, HPEXPIRE, and HPTTL methods. ```python redis.hset(hash_name, field, value) redis.hpexpire(hash_name, field, 1000) assert redis.hpttl(hash_name, field) == [950] # Example assertion ``` -------------------------------- ### Create a string index with nested fields Source: https://upstash.com/docs/redis/search/index-management Shows how to index string data types including nested schema fields and specific indexing options like no-tokenization or fast date indexing. ```TypeScript import { Redis, s } from "@upstash/redis"; const redis = Redis.fromEnv(); // String index with nested schema fields const comments = await redis.search.createIndex({ name: "comments", dataType: "string", prefix: "comment:", schema: s.object({ user: s.object({ name: s.string(), email: s.string().noTokenize(), }), comment: s.string(), upvotes: s.number(), commentedAt: s.date().fast(), }), }); ``` ```Python from upstash_redis import Redis redis = Redis.from_env() comments = redis.search.create_index( name="comments", data_type="string", prefix="comment:", schema={ "user.name": "TEXT", "user.email": {"type": "TEXT", "notokenize": True}, "comment": "TEXT", "upvotes": "U64", "commentedAt": {"type": "DATE", "fast": True}, }, ) ``` ```Redis CLI # String index with nested schema fields SEARCH.CREATE comments ON STRING PREFIX 1 comment: SCHEMA user.name TEXT user.email TEXT NOTOKENIZE comment TEXT upvotes U64 FAST commentedAt DATE FAST ``` -------------------------------- ### Install Upstash Redis SDK for Node.js Source: https://upstash.com/docs/redis/overall/llms-txt Installs the `@upstash/redis` package via npm, making it available for use in Node.js or edge environments. This is a common step for connecting to Upstash Redis from JavaScript applications. ```bash npm install @upstash/redis ``` -------------------------------- ### LPUSH Source: https://upstash.com/docs/redis/overall/llms-txt Prepends one or multiple values to the list. ```APIDOC ## LPUSH ### Description Prepends one or multiple values to the list. ### Method N/A ### Endpoint /redis/sdks/py/commands/list/lpush ### Parameters #### Path Parameters - **key** (string) - Required - The key of the list. - **values** (array) - Required - The values to prepend. ### Request Example ```json { "key": "mylist", "values": ["element0", "element-1"] } ``` ### Response #### Success Response (200) - **integer** (integer) - The length of the list after the push operation. #### Response Example ```json 5 ``` ``` -------------------------------- ### Perform GET request with Base64 encoding Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves a value from Redis via REST API with an optional base64 encoding header. Useful for binary data or specific transport requirements. ```shell curl https://your-upstash-redis-url.com/GET/foo \ -H "Authorization: Bearer YOUR_AUTH_TOKEN" \ -H "Upstash-Encoding: base64" ``` -------------------------------- ### POST /mset Source: https://upstash.com/docs/redis/overall/llms-txt Sets multiple key-value pairs in the Redis store simultaneously. ```APIDOC ## POST /mset ### Description Sets multiple key-value pairs in the Redis store. This operation is atomic. ### Method POST ### Endpoint /mset ### Parameters #### Request Body - **key1** (string) - Required - The first key to set. - **value1** (any) - Required - The value for the first key. - **key2** (string) - Required - The second key to set. - **value2** (any) - Required - The value for the second key. ### Request Example { "key1": "value1", "key2": "value2" } ### Response #### Success Response (200) - **result** (boolean) - True if all keys were set, False if at least one key was not set. #### Response Example { "result": true } ``` -------------------------------- ### Install FastAPI and Upstash Redis (Shell) Source: https://upstash.com/docs/redis/quickstarts/fastapi Installs the necessary Python packages for FastAPI and the Upstash Redis client. Ensure you have Python and pip installed. ```shell pip install fastapi pip install upstash-redis ``` -------------------------------- ### BITPOS Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Provides API documentation for the Redis BITPOS command, detailing its purpose, arguments, and response structure. ```APIDOC ## BITPOS Command ### Description Find the position of the first set or clear bit (bit with a value of 1 or 0) in a Redis string key. ### Method POST ### Endpoint (Not specified, typically part of a command execution endpoint) ### Parameters #### Arguments - **key** (string) - Required - The key to search in. - **bit** (0 | 1) - Required - The bit value to search for (0 or 1). - **start** (number) - Optional - The index to start searching at. - **end** (number) - Optional - The index to stop searching at. ### Request Example (Not provided in source, but would involve sending command details) ### Response #### Success Response (200) - **result** (integer) - The index of the first occurrence of the bit in the string. #### Response Example ```json 10 ``` ``` -------------------------------- ### Install Python Dependencies for Web Scraping Source: https://upstash.com/docs/redis/overall/llms-txt Installs essential Python packages including threading, requests, upstash-redis, and python-dotenv to support web scraping applications. ```bash pip install threading requests upstash-redis python-dotenv ``` -------------------------------- ### BitFieldCommands API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Documentation for the BitFieldCommands instance used for executing multiple chained bitfield operations in Redis. ```APIDOC ## BitFieldCommands API Reference ### Description Instance returned by the `redis.bitfield()` function for executing multiple bitfield operations. ### Arguments #### Path Parameters - **key** (str) - Required - The string key to operate on. ### Methods #### GET - **description**: Returns a value from the bitfield at the given offset. - **parameters**: - **type** (str) - e.g., 'u4', 'i8' - **offset** (int) #### SET - **description**: Sets a value and returns the old value. - **parameters**: - **type** (str) - **offset** (int) - **value** (int) #### INCR - **description**: Increments a value and returns the new value. - **parameters**: - **type** (str) - **offset** (int) - **increment** (int) ### Response - **type**: List[int] - **required**: true - **description**: A list of integers, one for each operation executed. ``` -------------------------------- ### Redis ZINTER Aggregation Example (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use the ZINTER command in Upstash Redis with Python to calculate the aggregated intersection of sets. This example includes scores and uses the SUM aggregation. ```APIDOC ## Redis ZINTER Aggregation Example (Python) ### Description Shows how to use the ZINTER command in Upstash Redis with Python to calculate the aggregated intersection of sets. This example includes scores and uses the SUM aggregation. ### Method ZINTER (via Python SDK) ### Endpoint N/A ### Parameters None ### Request Example ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zunion(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ``` ### Response #### Success Response (200) - **result** (list of tuples) - A list of tuples, where each tuple contains a member and its aggregated score from the intersection of the specified sets. ``` -------------------------------- ### Install Upstash Redis Python Package Source: https://upstash.com/docs/redis/overall/llms-txt Installs the upstash-redis Python package using pip. This is the initial step for using the library in Python projects. ```bash pip install upstash-redis ``` -------------------------------- ### Decrement Values with DECR and DECRBY Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to decrement integer values stored in Redis keys. Includes examples for both single-unit decrement (DECR) in Python and custom-amount decrement (DECRBY) in TypeScript. ```typescript await redis.set("key", 6); await redis.decrby("key", 4); // returns 2 ``` ```python redis.set("key", 6) assert redis.decr("key") == 5 ``` -------------------------------- ### Initialize Multi-Regional Sliding Window Ratelimiter Source: https://upstash.com/docs/redis/overall/llms-txt Configures a multi-regional rate limiter using the Sliding Window algorithm. Note that this approach is resource-intensive and the Fixed Window algorithm is generally recommended for multi-region setups. ```typescript const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({ /* auth */ }), new Redis({ /* auth */ }) ], limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"), }); ``` -------------------------------- ### GET/POST /websites/upstash-redis/blockUntilReady Source: https://upstash.com/docs/redis/overall/llms-txt This method operates identically to the limit() method regarding command execution and Redis interactions. ```APIDOC ## GET/POST /websites/upstash-redis/blockUntilReady ### Description This method operates identically to the `limit()` method regarding command execution and Redis interactions. ### Method GET/POST ### Endpoint /websites/upstash-redis/blockUntilReady ### Parameters - **Refer to limit() documentation** (N/A) - Required - Parameters are the same as the `limit()` method. ### Response #### Success Response (200) - **Response** (any) - Response structure is the same as the `limit()` method. ``` -------------------------------- ### TypeScript Sorted Set Operations Example (ZADD, ZRANK) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates adding members to a sorted set using `redis.zadd` and then attempting to retrieve a value using `redis.zrank`. Note: The example's output comment `// 2` is inconsistent with `zrank`'s typical return value, which is a member's rank, not the set's cardinality. This code snippet demonstrates basic sorted set manipulation. ```APIDOC ```TypeScript await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" } ); const elements = await redis.zrank("key"); console.log(elements); // 2 ``` ``` -------------------------------- ### RANDOMKEY /api/redis/randomkey Source: https://upstash.com/docs/redis/overall/llms-txt Return a random key from the keyspace. ```APIDOC ## RANDOMKEY /api/redis/randomkey ### Description Return a random key from the keyspace. ### Method RANDOMKEY ### Endpoint /api/redis/randomkey ### Parameters None ### Request Example {} ### Response #### Success Response (200) - **key** (string) - The name of a random key, or null if the database is empty. #### Response Example { "key": "somekey" } ``` -------------------------------- ### MSETNX Command Source: https://upstash.com/docs/redis/overall/llms-txt API documentation for the MSETNX command, detailing its purpose, arguments, and response format. MSETNX allows setting multiple keys simultaneously only if none of them already exist. ```APIDOC ## MSETNX Command ### Description Set multiple keys in one go unless they exist already. Counts as a single command for billing. ### Method POST ### Endpoint /redis/v1/msetnx ### Parameters #### Path Parameters None #### Query Parameters - **key** (string) - Required - The key to set. - **value** (any) - Required - The value to set for the key. ### Request Example ```json { "key1": "value1", "key2": "value2" } ``` ### Response #### Success Response (200) - **result** (integer) - Returns 1 if all keys were set, 0 if no keys were set (because at least one key already existed). ``` -------------------------------- ### ZINTERSTORE with Sum Aggregation in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates using the 'aggregate' option with redis.zinterstore in TypeScript to combine scores when multiple input sets share members. This example uses 'sum' aggregation. ```typescript // Assuming 'redis' is an initialized Upstash Redis client 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 ``` -------------------------------- ### Build Project (Maven) Source: https://upstash.com/docs/redis/tutorials/serverless_java_redis Builds the Java project using Maven. This command compiles the code, runs tests, and packages the application into a JAR file. ```shell mvn clean install ``` -------------------------------- ### Redis SET Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Provides detailed documentation for the Redis SET command, outlining its required and optional arguments, their types, descriptions, and the expected response. This API reference is useful for understanding the full capabilities of the SET command. ```apidoc SET Command: Description: Set a key to hold a string value. Arguments: key: Type: string Required: true Description: The key to set. value: Type: TValue Required: true Description: The value to store. Non-string values are JSON.stringify'd. opts (Optional): Type: object Description: Options to modify SET behavior. Options: get: Type: boolean Description: Returns the old value at key, or null if key did not exist, instead of 'OK'. ex: Type: integer Description: Sets an expiration in seconds. px: Type: integer Description: Sets an expiration in milliseconds. exat: Type: integer Description: Sets an expiration at a specific Unix timestamp (seconds). pxat: Type: integer Description: Sets an expiration at a specific Unix timestamp (milliseconds). keepTtl: Type: boolean Description: Preserves the existing TTL if the key already exists. nx: Type: boolean Description: Only sets the key if it does not already exist. xx: Type: boolean Description: Only sets the key if it already exists. Response: Type: string Value: "OK" (default) or old value (if 'get' option is used) Description: Returns 'OK' on success, or the old value if 'get' option is specified. ``` -------------------------------- ### POST /pipeline Source: https://upstash.com/docs/redis/overall/llms-txt Send multiple Redis commands as a batch to the Upstash /pipeline endpoint to reduce latency. ```APIDOC ## POST /pipeline ### Description Send multiple Redis commands as a batch to the Upstash /pipeline endpoint. ### Method POST ### Endpoint /pipeline ### Parameters #### Request Body - **commands** (Array>) - Required - A two-dimensional JSON array where each inner array represents a Redis command and its arguments. ### Request Example ```shell curl -X POST https://YOUR_UPSTASH_ENDPOINT/pipeline \ -H "Authorization: Bearer $TOKEN" \ -d ' [ ["CMD_A", "arg0", "arg1", ..., "argN"], ["CMD_B", "arg0", "arg1", ..., "argM"], ... ] ' ``` ### Response #### Success Response (200) - **result** (Array) - An array containing the results of each executed command. ``` -------------------------------- ### Environment Variable Configuration (Text) Source: https://upstash.com/docs/redis/overall/llms-txt Example format for environment variables storing Upstash Redis connection details. These should be kept secure and not committed to version control. ```text UPSTASH_REDIS_REST_URL=**** UPSTASH_REDIS_REST_TOKEN=**** ``` -------------------------------- ### MSETNX Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Provides API documentation for the MSETNX command, which sets multiple keys simultaneously only if none of them already exist. This functionality is available in both Python and TypeScript SDKs. It details arguments and the boolean response indicating success. ```APIDOC MSETNX Command: Description: Set multiple keys in one go unless they exist already. Counts as a single command for billing. Arguments: ParamField: type: Record required: true description: An object where the keys are the keys to set, and the values are the values to set. Response: ResponseField: type: boolean required: true description: True if all keys were set, False if at least one key was not set. ``` ```APIDOC MSETNX Command: Description: Set multiple keys in one go unless they exist already. Counts as a single command for billing. Arguments: - name: keysAndValues type: Record required: true description: An object where the keys are the keys to set, and the values are the values to set. Response: type: number description: '1' if all keys were set, '0' if at least one key was not set. ``` -------------------------------- ### Increment Hash Field Value (HINCRBY) Source: https://upstash.com/docs/redis/overall/llms-txt This example demonstrates how to use the `HINCRBY` command with Upstash Redis in TypeScript to increment a hash field's value. If the field or hash does not exist, it is created. ```APIDOC ## Increment Hash Field Value (HINCRBY) ### Description Increments the integer value of a hash field by a specified amount. If the field or hash does not exist, it is created with the value after the increment. ### Method hset, hincrby ### Endpoint Not applicable (command-based) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' client is initialized await redis.hset("key", { field: 20, }); const after = await redis.hincrby("key", "field", 2); console.log(after); // Expected output: 22 ``` ### Response #### Success Response (200) - **result** (integer) - The new integer value of the hash field after the increment. ``` -------------------------------- ### HSETEX Command Documentation Source: https://upstash.com/docs/redis/sdks/ts/commands/hash/hsetex This section details the HSETEX command, its parameters, and provides various usage examples. ```APIDOC ## POST /websites/upstash_redis ### Description Sets multiple fields in a hash, with optional expiration and conditional behavior. It returns the number of fields that were set. ### Method POST ### Endpoint /websites/upstash_redis ### Parameters #### Query Parameters - **cmd** (string) - Required - The command to execute, e.g., `HSETEX`. - **key** (string) - Required - The key of the hash. - **options** (object) - Optional - An object containing expiration and/or conditional options. - **expiration** (object) - Optional - Specifies the expiration time. - **ex** (number) - Expires in seconds. - **px** (number) - Expires in milliseconds. - **exat** (number) - Expires at a specific Unix timestamp (seconds). - **pxat** (number) - Expires at a specific Unix timestamp (milliseconds). - **keepttl** (boolean) - Retains the existing TTL of the hash. - **conditional** (string) - Optional - Specifies conditional behavior. - **FNX**: Only set if the hash does not exist. - **FXX**: Only set if the hash already exists. #### Request Body - **fields** (object) - Required - An object where keys are field names and values are field values. ### Request Example ```json { "cmd": "HSETEX", "key": "user:123", "options": { "expiration": { "ex": 3600 } }, "fields": { "name": "John", "email": "john@example.com" } } ``` ### Response #### Success Response (200) - **result** (number) - The number of fields that were set. Returns 0 if conditions are not met. #### Response Example ```json { "result": 2 } ``` ### Use Cases * **Session Management**: Create sessions with automatic expiration. * **Cache with TTL**: Store cached data that expires automatically. * **Temporary Data**: Create temporary records with built-in cleanup. * **Rate Limiting**: Store rate limit counters with automatic reset. * **Conditional Updates**: Ensure data consistency with FNX/FXX options. ``` -------------------------------- ### Get Random Field with Value from Hash (HRANDFIELD) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates fetching a random field along with its value from a Redis hash using the HRANDFIELD command with the 'withvalues' argument. This returns a dictionary-like object. ```APIDOC ## Get Random Field with Value from Hash (HRANDFIELD) ### Description Returns a random field and its value from the hash stored at key. If count is positive, N fields and their values are returned. If count is negative, N random fields are returned with their values. ### Method HRANDFIELD ### Endpoint Not applicable (command-based) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Arguments - **key** (string) - Required - The key of the hash. - **count** (integer) - Optional - The number of fields to return. If positive, returns fields and values. If negative, returns only fields. - **withvalues** (boolean) - Optional - If true, returns fields and values. Ignored if count is negative. ### Request Example ```python # Assuming 'redis' client is initialized redis.hset("myhash", values={"field1": "Hello", "field2": "World"}) # Get one random field and its value result = redis.hrandfield("myhash", count=1, withvalues=True) # Example assertion (result could be either {'field1': 'Hello'} or {'field2': 'World'}) assert result in [{"field1": "Hello"}, {"field2": "World"}] ``` ### Response #### Success Response (200) - **result** (dict or list of dicts) - A dictionary-like object containing the random field(s) and their values. ``` -------------------------------- ### Connect to Upstash Redis with Redisson (Java) Source: https://upstash.com/docs/redis/overall/llms-txt This Java code snippet demonstrates how to initialize the Redisson client, connect to an Upstash Redis instance using a password and endpoint, and perform a basic `put` and `get` operation on a distributed map (`RMap`). Remember to replace placeholders for password and endpoint, and use `rediss://` for SSL connections. ```java import org.redisson.Redisson; import org.redisson.api.RMap; import org.redisson.config.Config; 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")); } } ``` -------------------------------- ### SUNION Command (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Returns the union of all the given sets. ```APIDOC ## SUNION Command (Python) ### Description Returns the union of all the given sets. This command computes the union of sets stored at the keys. ### Method `redis.sunion(key1: str, key2: str, ...keys: str): Set[str]` ### Endpoint N/A (SDK Method) ### Parameters #### Request Body - **keys** (string[]) - Required - Keys of the sets to union. ### Request Example ```python union_set = redis.sunion("key1", "key2") ``` ### Response #### Success Response - **Set[str]**: A set containing all elements from the input sets. #### Response Example ```json {"a", "b", "c", "d", "e"} ``` ``` -------------------------------- ### Configure Upstash MCP SSE Server Source: https://upstash.com/docs/redis/overall/llms-txt JSON configuration for deploying the Upstash MCP server in SSE mode using a supergateway proxy. Includes examples for both mcpServers and standard server definitions. ```json { "mcpServers": { "upstash": { "command": "npx", "args": [ "-y", "supergateway", "--sse", "https://mcp.upstash.io/sse", "--oauth2Bearer", ":" ] } } } ``` ```json { "servers": { "upstash": { "type": "stdio", "command": "npx", "args": [ "-y", "supergateway", "--sse", "https://mcp.upstash.io/sse", "--oauth2Bearer", ":" ] } } } ``` -------------------------------- ### LRANGE Redis Command API Specification Source: https://upstash.com/docs/redis/overall/llms-txt Defines the API structure for the LRANGE command, which retrieves a range of elements from a list. It outlines required arguments like key, start, and end indices. ```apidoc LRANGE: description: Returns the specified elements of the list stored at key. Arguments: key: type: string required: true description: The key of the list. start: type: integer required: true description: The starting index of the range to return. Use negative numbers to specify offsets starting at the end of the list. end: type: integer required: true description: The ending index of the range to return. Use negative numbers to specify offsets starting at the end of the list. Response: type: TValue[] required: true description: The list of elements in the specified range. ``` -------------------------------- ### TypeScript List Manipulation (LTRIM) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates initializing a list with LPUSH and trimming it to a specific range using LTRIM. ```typescript await redis.lpush("key", "a", "b", "c", "d"); await redis.ltrim("key", 1, 2); // the list is now ["b", "c"] ``` -------------------------------- ### Configure Serverless Framework for AWS Lambda Source: https://upstash.com/docs/redis/overall/llms-txt Defines the AWS provider, Node.js runtime, and environment variables for a Serverless Framework service. It configures a 'counter' function triggered by an HTTP GET request. ```yaml 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 ``` -------------------------------- ### POST /record (Serverless API) Source: https://upstash.com/docs/redis/overall/llms-txt Endpoint for recording data into the Redis instance via a Serverless function. ```APIDOC ## POST /record ### Description Records data into the Redis store using a serverless function handler. ### Method POST ### Endpoint `/record` ### Request Example ```json { "data": "example_payload" } ``` ### Response #### Success Response (200) - **status** (string) - Confirmation of the record operation. ``` -------------------------------- ### Python HPEXPIREAT Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates setting an expiration time in milliseconds for a field within a Redis hash using the `hpexpireat` command in Python. It requires the `redis` client and `time` module. ```python import time # Assuming 'redis' is a configured Redis client instance and hash_name, field, value are defined redis.hset(hash_name, field, value) assert redis.hpexpireat(hash_name, field, int(time.time() * 1000) + 1000) == [1] ``` -------------------------------- ### Deno Redis Client Setup Source: https://upstash.com/docs/redis/overall/llms-txt Initializes the Upstash Redis client for Deno environments, including Deno Deploy and Netlify Edge. The client can be configured with explicit URL and token, or loaded directly from environment variables using `Redis.fromEnv()`. ```typescript import { Redis } from "https://deno.land/x/upstash_redis/mod.ts" const redis = new Redis({ url: , token: , }) // or const redis = Redis.fromEnv(); ``` -------------------------------- ### Add Bull to Project Dependencies Source: https://upstash.com/docs/redis/tutorials/job_processing This command installs the Bull library, a popular Redis-based queue for Node.js, into your project. Bull is used for managing the task queue in this example. ```shell npm install bull ``` -------------------------------- ### XRANGE Command Source: https://upstash.com/docs/redis/overall/llms-txt Documents the XRANGE command for Redis streams, detailing its required arguments and response structure. ```APIDOC ## XRANGE Command ### Description Returns stream entries matching a given range of IDs. ### Method GET ### Endpoint /stream/{key} ### Parameters #### Path Parameters - **key** (str) - Required - The key of the stream. #### Query Parameters - **start** (str) - Required - The stream entry ID to start from. - **end** (str) - Required - The stream entry ID to end at. - **count** (int) - Optional - The maximum number of entries to return. ### Request Example { "command": "XRANGE", "key": "my_stream", "start": "0-0", "end": "+", "count": 10 } ### Response #### Success Response (200) - **Record>** - An object of stream entries, keyed by their stream ID. #### Response Example { "1678881120000-0": { "sensor-id": "123", "temperature": "25.5" } } ``` -------------------------------- ### Navigate Project Directory via Shell Source: https://upstash.com/docs/redis/overall/llms-txt A standard shell command to change the current working directory to a specific project folder. ```Shell cd aws-java-counter-api ``` -------------------------------- ### Block until ready with SlidingWindow Source: https://upstash.com/docs/redis/sdks/ratelimit-py/features Demonstrates how to use the block_until_ready method to wait for a request to be allowed within a specified timeout period. This is useful for managing traffic spikes by queuing requests until the next window opens. ```python 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") else: do_expensive_calculation() print("Here you go!") ``` -------------------------------- ### Run the URL shortener application Source: https://upstash.com/docs/redis/tutorials/python_url_shortener Command to execute the Python script and verify the output. ```shell python url_shortener.py ``` -------------------------------- ### Verify Upstash QStash Webhook Signature (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the Upstash QStash receiver to verify incoming webhook signatures. Requires the '@upstash/qstash' package and signing key environment variables. ```typescript import { Receiver } from "@upstash/qstash"; const receiver = new Receiver({ currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY, nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY, }); const isValid = await receiver.verify({ signature: "..." body: "..." }) ``` -------------------------------- ### Evaluate Lua Scripts with Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to execute server-side Lua scripts using the eval method in Python. This allows for atomic operations and complex logic directly within the Redis instance. ```python script = """ local value = redis.call("GET", KEYS[1]) return value """ redis.set("mykey", "Hello") assert redis.eval(script, keys=["mykey"]) == "Hello" ``` -------------------------------- ### Python Redis HEXPIRE Command Example Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the use of the HEXPIRE command in Python to set an expiration time for a hash in Redis. The time is specified in seconds. Requires an initialized Redis client. ```python response = r.hexpire("myhash", 60) ``` -------------------------------- ### Configure Apollo Client in Next.js Source: https://upstash.com/docs/redis/tutorials/coin_price_list Sets up the Apollo Client provider in the Next.js _app.js file, configuring the GraphQL endpoint and authorization headers for read-only access. ```javascript import "../styles/globals.css"; import { ApolloClient, ApolloProvider, createHttpLink, InMemoryCache, } from "@apollo/client"; const link = createHttpLink({ uri: "https://graphql-us-east-1.upstash.io/", headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN", }, }); const client = new ApolloClient({ uri: "https://graphql-us-east-1.upstash.io/", cache: new InMemoryCache(), link, }); function MyApp({ Component, pageProps }) { return ( {" "} ); } export default MyApp; ``` -------------------------------- ### Install Flask and Upstash Redis Client (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Installs the necessary Python packages for Flask and the Upstash Redis client using pip. This is required for Flask applications using Upstash Redis. ```shell pip install flask pip install upstash-redis ``` -------------------------------- ### Resolve ReferenceError: fetch is not defined in Node.js Source: https://upstash.com/docs/redis/overall/llms-txt Addresses the 'ReferenceError: fetch is not defined' issue in Node.js environments (v17 and earlier) where `fetch` is not natively supported. It provides a solution by installing and importing `isomorphic-fetch` as a polyfill. ```APIDOC ## Resolve ReferenceError: fetch is not defined in Node.js ### Description Addresses the 'ReferenceError: fetch is not defined' issue in Node.js environments (v17 and earlier) where `fetch` is not natively supported. It provides a solution by installing and importing `isomorphic-fetch` as a polyfill. ### Method NPM Package Installation & TypeScript ### Endpoint N/A ### Parameters None ### Request Example ```bash npm i isomorphic-fetch ``` ```typescript import { Redis } from "@upstash/redis"; import "isomorphic-fetch"; const redis = new Redis({ /*...*/ }); ``` ### Response Success Response (200) - The `fetch` function is now available in the Node.js environment. ``` -------------------------------- ### SET Command Source: https://upstash.com/docs/redis/overall/llms-txt Set a key to hold a string value. ```APIDOC ## SET ### Description Set a key to hold a string value. ### Method SET ### Parameters #### Request Body - **key** (str) - Required - The key to set. - **value** (str) - Required - The value to store. ### Response #### Success Response (200) - **status** (string) - Returns 'OK' on success. ``` -------------------------------- ### Polyfill Fetch API in Node.js (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Addresses the 'ReferenceError: fetch is not defined' in Node.js environments (v17 and earlier) where `fetch` is not natively supported. This solution involves installing and importing the `isomorphic-fetch` package as a polyfill. ```bash npm i isomorphic-fetch ``` ```typescript import { Redis } from "@upstash/redis"; import "isomorphic-fetch"; const redis = new Redis({ /*...*/ }); ``` -------------------------------- ### Placeholder for Next.js Survey Application Source: https://upstash.com/docs/redis/overall/llms-txt A placeholder snippet for implementing survey data management logic within a Next.js application using Upstash Redis. ```JavaScript console.log('This is a placeholder for Next.js code related to survey app.'); ``` -------------------------------- ### Redis BitField Commands API Reference (APIDOC) Source: https://upstash.com/docs/redis/overall/llms-txt Defines the BitFieldCommands instance for executing multiple bitfield operations in Redis. It specifies methods like 'get', 'set', and 'incr' with their parameters and response structures. ```apidoc BitFieldCommands: description: Instance returned by the `redis.bitfield()` function for executing multiple bitfield operations. arguments: key: type: str required: true description: The string key to operate on. response: type: List[int] required: true description: A list of integers, one for each operation executed. methods: get(type: str, offset: int) description: Returns a value from the bitfield at the given offset. parameters: type: str (e.g., 'u4', 'i8') offset: int set(type: str, offset: int, value: int) description: Sets a value and returns the old value. parameters: type: str offset: int value: int incr(type: str, offset: int, increment: int) description: Increments a value and returns the new value. parameters: type: str offset: int increment: int ``` -------------------------------- ### Manage sorted sets and lexicographical counts in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates adding members to a sorted set via ZADD and counting elements within a range using ZLEXCOUNT. ```json { "key": "myset", "members": {"a": 1, "b": 2, "c": 3} } ``` ```json 3 ``` -------------------------------- ### Create Phoenix App without Ecto Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a new Phoenix application configured to use Redis for data storage instead of Ecto. ```APIDOC ## Create a new Phoenix Elixir application without Ecto ### Description Initializes a new Phoenix application named `redix_demo` without Ecto, configured to use Redis for data storage. ### Command ```shell mix phx.new redix_demo --no-ecto ``` ``` -------------------------------- ### Initialize Upstash Redis Client in Node.js/Browser Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to initialize the Upstash Redis client in Node.js or browser environments. It provides two methods: using explicit URL and token, or loading configuration directly from environment variables using `Redis.fromEnv()`, which is recommended for serverless platforms. ```typescript import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // or load directly from env const redis = Redis.fromEnv() ``` -------------------------------- ### Implement Read-Your-Writes Pattern (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates a pattern for managing read and write operations in TypeScript. Highlights potential consistency considerations when using separate client instances for read and write requests. ```typescript 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; }; const randomKey = await writeRequest(); await readRequest(randomKey); ``` -------------------------------- ### Shorten and Retrieve URLs in Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates a workflow for shortening a URL with an expiration time and subsequently retrieving the original URL using helper functions. ```python if __name__ == "__main__": original_url = "https://example.com/my-very-long-url" short_url = shorten_url(original_url, expiration=600) print(f"Shortened URL: {short_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") ``` -------------------------------- ### BITCOUNT Command Source: https://upstash.com/docs/redis/overall/llms-txt Counts the number of set bits (1s) in a binary string stored at a given key. You can optionally specify a range (start and end) to count bits within a specific portion of the string. ```APIDOC ## BITCOUNT ### Description Counts the number of set bits (1s) in a binary string stored at a given key. You can optionally specify a range (start and end) to count bits within a specific portion of the string. ### Method GET (or equivalent for command execution) ### Endpoint `/redis/v1/cmd` (Illustrative, actual endpoint may vary based on client library) ### Parameters #### Query Parameters - **cmd** (string) - Required - The Redis command to execute, e.g., `BITCOUNT key [start end]` #### Path Parameters None #### Request Body None (Command and arguments are typically passed as query parameters or within the command string itself) ### Request Example ```python # Assuming 'redis' is an Upstash Redis client instance # Set some bits redis.setbit("mykey", 7, 1) redis.setbit("mykey", 8, 1) redis.setbit("mykey", 9, 1) # Count bits within a range (bytes 0 to 10) response_with_range = redis.execute_command("BITCOUNT", "mykey", 0, 10) print(response_with_range) # Output: 3 # Count all bits in the string response_without_range = redis.execute_command("BITCOUNT", "mykey") print(response_without_range) # Output: 3 ``` ### Response #### Success Response (200) - **count** (integer) - The number of set bits in the specified range or the entire string. #### Response Example ```json { "result": "3" } ``` ``` -------------------------------- ### Redis Command Operations Source: https://upstash.com/docs/redis/overall/llms-txt Common Redis operations including SADD, JSON.CLEAR, HMGET, LLEN, FLUSHALL, and SCARD. ```APIDOC ## Redis Command Operations ### Description Collection of standard Redis commands for data manipulation and server management. ### Methods Various (SADD, JSON.CLEAR, HMGET, LLEN, FLUSHALL, SCARD) ### Examples - **SADD**: `redis.sadd("key", "a", "b", "c")` - **JSON.CLEAR**: `redis.json.clear("key", "$.my.key")` - **HMGET**: `redis.hmget("myhash", "field1", "field2")` - **LLEN**: `redis.llen("key")` - **FLUSHALL**: `redis.flushall(flush_type="ASYNC")` - **SCARD**: `redis.scard("key")` ``` -------------------------------- ### Fetch data in Next.js Server Component Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the initialized Redis client within a Next.js server component to retrieve data. ```APIDOC ## Fetch data in Next.js Server Component ### Description Demonstrates how to use the initialized Redis client within a Next.js server component to retrieve data. ### Method Client-side command execution (within Next.js Server Component) ### Endpoint N/A (Client-side operation) ### Parameters #### Redis Client Parameters - **key** (string) - Required - The key for the data to retrieve. ### Request Example (Code Snippet) ```typescript import { redis } from "@/lib/redis" const Page = async () => { const count = await redis.get("count") return

count: {count}

} export default Page ``` ### Response #### Success Response - **count** (number | null) - The retrieved value associated with the key, or null if the key does not exist. ``` -------------------------------- ### Example Lambda Test Event Source: https://upstash.com/docs/redis/overall/llms-txt A sample JSON payload structure used to simulate input for AWS Lambda functions interacting with Redis. ```json { "key": "foo", "value": "bar" } ``` -------------------------------- ### Initialize AWS SAM Project Source: https://upstash.com/docs/redis/tutorials/using_aws_sam Commands to initialize a new AWS SAM project using the CLI and navigate into the project directory. ```shell sam init cd sam-app ``` -------------------------------- ### Package AWS Lambda Function Source: https://upstash.com/docs/redis/howto/getstartedawslambda Command to create a deployment package for an AWS Lambda function including dependencies. ```bash zip -r app.zip . ``` -------------------------------- ### Flask Application with Upstash Redis Counter (Python) Source: https://upstash.com/docs/redis/quickstarts/flask A simple Flask application that initializes a connection to Upstash Redis using environment variables and increments a 'counter' key on each homepage visit. The current count is then displayed. ```python from flask import Flask from upstash_redis import Redis app = Flask(__name__) redis = Redis.from_env() @app.route('/') def index(): count = redis.incr('counter') return f'Page visited {count} times.' if __name__ == '__main__': app.run(debug=True) ``` -------------------------------- ### Perform ZINTER operations in Python Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to calculate the intersection of sorted sets using custom weights and aggregation in Python. ```python 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)] ``` -------------------------------- ### ZUNIONSTORE Command Source: https://upstash.com/docs/redis/overall/llms-txt Combines multiple sorted sets into a new sorted set. Supports options for weights and aggregation. ```APIDOC ## ZUNIONSTORE Command ### Description Combines multiple sorted sets into a new sorted set. Supports options for weights and aggregation. ### Method POST (or equivalent for command execution) ### Endpoint `/redis/commands/zset/zunionstore` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **destination** (string) - Required - The key of the new sorted set. - **numkeys** (number) - Required - The number of input sorted sets. - **keys** (Array) - Required - An array of keys of the input sorted sets. - **options** (object) - Optional - Options for weights and aggregation. - **weights** (Array) - Optional - Weights to apply to each input set. - **aggregate** (string) - Optional - Aggregation method ('SUM', 'MIN', 'MAX'). ### Request Example (Basic Union) ```typescript await redis.zunionstore("destination", 2, ["key1", "key2"]); ``` ### Request Example (With Weights) ```typescript await redis.zunionstore("destination", 2, ["key1", "key2"], { weights: [2, 3] }); ``` ### Request Example (With Aggregation) ```typescript await redis.zunionstore("destination", 2, ["key1", "key2"], { aggregate: "sum" }); ``` ### Response #### Success Response (200) - **result** (number) - The number of elements in the new sorted set. ``` -------------------------------- ### Read Stream Data with XREAD Source: https://upstash.com/docs/redis/overall/llms-txt Reads messages from one or more Redis streams starting from specific IDs. The request accepts a dictionary of stream keys and an optional count to limit the number of messages returned. ```json { "streams": {"mystream": "0-0"}, "count": 10 } ``` -------------------------------- ### Initialize Fastly Compute Project Source: https://upstash.com/docs/redis/quickstarts/fastlycompute Commands to initialize a new Fastly Compute project using the CLI and install the necessary Upstash Redis dependency. ```shell fastly compute init npm install @upstash/redis ``` -------------------------------- ### Test API Endpoints with cURL Source: https://upstash.com/docs/redis/tutorials/laravel_caching Example cURL commands to interact with the Todo API, demonstrating GET, POST, PUT, and DELETE operations. ```shell curl http://todo-cache.test/api/todos curl http://todo-cache.test/api/todos/1 curl -X POST http://todo-cache.test/api/todos -H "Content-Type: application/json" -d '{"title":"New Todo"}' curl -X PUT http://todo-cache.test/api/todos/1 -H "Content-Type: application/json" -d '{"title":"Updated Todo"}' curl -X DELETE http://todo-cache.test/api/todos/1 ``` -------------------------------- ### Retrieve Redis List Range Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to fetch a range of elements from a Redis list using the LRANGE command. The request requires a key, start index, and end index, returning an array of values. ```json { "command": "LRANGE", "key": "my_list_key", "start": 0, "end": -1 } ``` -------------------------------- ### Create Project Directory and Navigate Source: https://upstash.com/docs/redis/tutorials/pythonapi Initializes a new project directory for the AWS CDK application and navigates into it. This directory name is used by the CDK CLI for naming resources. ```shell mkdir counter-cdk && cd counter-cdk ``` -------------------------------- ### Python: Retrieve Keys with redis.keys() Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to use the `redis.keys()` method in Python to fetch keys from Upstash Redis, including matching keys by prefix and retrieving all keys. Caution is advised for `keys('*')` on large datasets. ```APIDOC ## Python: Retrieve Keys with redis.keys() ### Description Illustrates how to use the `redis.keys()` method in Python to fetch keys from Upstash Redis. Examples include matching keys by a specific prefix and retrieving all keys. Be cautious when using `keys('*')` in production environments as it can impact performance on large datasets. ### Method GET ### Endpoint (Assumed Upstash Redis endpoint) ### Parameters * **pattern** (string) - Optional - A glob-style pattern to match keys against. Defaults to '*'. ### Request Example ```python # Fetch keys with a specific prefix keys = redis.keys("prefix*") # Fetch all keys (use with caution on large datasets) keys = redis.keys("*") ``` ### Response #### Success Response - **keys** (list of strings) - A list of keys matching the pattern. ``` -------------------------------- ### Monitor pending stream messages with XPENDING Source: https://upstash.com/docs/redis/overall/llms-txt Returns information about pending messages in a stream consumer group. It can be used to get a summary or detailed pending message information based on provided range arguments. ```python # Summary redis.xpending("mystream", "mygroup") # Detailed with range redis.xpending("mystream", "mygroup", start="-", end="+", count=10) # Specific consumer with idle filter redis.xpending("mystream", "mygroup", start="-", end="+", count=5, consumer="consumer1", idle=10000) ``` -------------------------------- ### SUNIONSTORE Command Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/set/sunionstore Demonstrates how to use the SUNIONSTORE command to perform a set union and store the result in a new key. It requires the 'redis' library and assumes prior set creation. ```python redis.sadd("set1", "a", "b", "c"); redis.sadd("set2", "c", "d", "e"); redis.sunionstore("destination", "set1", "set2") ``` -------------------------------- ### Configure Upstash MCP via Claude CLI Source: https://upstash.com/docs/redis/overall/llms-txt Provides bash commands to register the Upstash MCP server using the Claude CLI. It covers adding the server with global or project-specific scopes, utilizing npx for installation. ```bash claude mcp add upstash -- npx -y @upstash/mcp-server@latest \ --email \ --api-key ``` ```bash claude mcp list ``` ```bash claude mcp add upstash --scope project -- npx -y @upstash/mcp-server@latest \ --email \ --api-key ``` -------------------------------- ### Retrieve Keys using Python SDK Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to fetch keys from Upstash Redis using the Python SDK's keys method. Supports both pattern-based matching and retrieving all keys. ```python # Retrieve keys with a specific prefix keys = redis.keys("prefix*") # Retrieve all keys keys = redis.keys("*") ``` -------------------------------- ### Install Upstash Redis SDK Source: https://upstash.com/docs/redis/howto/connectwithupstashredis Command to install the @upstash/redis package via npm for use in Node.js or edge environments. ```bash npm install @upstash/redis ``` -------------------------------- ### Redis SMEMBERS Command Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves all members from a specified Redis set. ```APIDOC ## SMEMBERS ### Description Return all the members of a set. ### Method Command ### Endpoint N/A ### Parameters #### Arguments - **key** (str) - Required - The key of the set. ### Response #### Success Response (200) - **members** (set[str]) - The members of the set. ### Request Example ```python redis.sadd("set", "a", "b", "c"); assert redis.smembers("set") == {"a", "b", "c"} ``` ``` -------------------------------- ### Python Example for ZDIFFSTORE Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zdiffstore Demonstrates how to use the ZDIFFSTORE command in Python to find the difference between two Redis sets and store the result in a destination key. This requires the 'redis-py' library. ```python 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 ``` -------------------------------- ### Create Upstash Redis Database Source: https://upstash.com/docs/redis/overall/llms-txt Creates a new Upstash Redis database with specified configuration using the Upstash API. ```APIDOC ## Create Upstash Redis Database ### Description Creates a new Upstash Redis database with specified configuration. ### Method POST ### Endpoint https://api.upstash.com/v2/redis/database ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body - **name** (string) - Required - The name of the database. - **region** (string) - Required - The global region for the database (e.g., "global"). - **primary_region** (string) - Required - The primary AWS region for the database (e.g., "us-east-1"). - **read_regions** (array of strings) - Optional - List of AWS regions for read replicas (e.g., ["us-west-1","us-west-2"]) - **tls** (boolean) - Optional - Enable TLS for the database connection. ### Authentication Basic Authentication using `EMAIL:API_KEY`. ### Request Example ```bash curl -X POST \ https://api.upstash.com/v2/redis/database \ -u 'EMAIL:API_KEY' \ -d '{"name":"myredis", "region":"global", "primary_region":"us-east-1", "read_regions":["us-west-1","us-west-2"], "tls": true}' ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique identifier of the created database. - **name** (string) - The name of the database. - **region** (string) - The global region of the database. - **primary_region** (string) - The primary AWS region. - **read_regions** (array of strings) - List of read replica regions. - **tls** (boolean) - TLS status. - **connection_urls** (object) - Object containing connection URLs (e.g., `['redis', 'rediss']`). #### Response Example ```json { "id": "some-database-id", "name": "myredis", "region": "global", "primary_region": "us-east-1", "read_regions": [ "us-west-1", "us-west-2" ], "tls": true, "connection_urls": { "redis": "redis://...", "rediss": "rediss://..." } } ``` ``` -------------------------------- ### Implement Feature Flags in Next.js with Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to implement feature flags in a Next.js application using Upstash Redis. This involves checking the status of a feature flag stored in Redis to dynamically toggle features. The example includes a function to check feature status and a usage example within a component. ```APIDOC ```javascript // Example feature flag check async function isFeatureEnabled(featureName) { const enabled = await redis.get(`feature:${featureName}`); return enabled === 'true'; } // Usage in a component if (await isFeatureEnabled('new_dashboard')) { // Show new dashboard } else { // Show old dashboard } ``` ``` -------------------------------- ### Fetch Stream Entries with XRANGE in Python Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xrange Demonstrates how to use the XRANGE command to retrieve stream entries. It supports fetching all entries, a specific range of IDs, or a limited number of results. ```python result = redis.xrange("mystream", "-", "+") ``` ```python result = redis.xrange("mystream", "1548149259438-0", "1548149259438-5") ``` ```python result = redis.xrange("mystream", "-", "+", count=10) ``` -------------------------------- ### POST /set Source: https://upstash.com/docs/redis/overall/llms-txt Sets a value for a specific key in Redis with optional configurations for expiration and conditional updates. ```APIDOC ## POST /set ### Description Sets the value of a key in Redis. Supports optional expiration (seconds/milliseconds) and conditional logic (NX/XX). ### Method POST ### Endpoint /set ### Parameters #### Request Body - **key** (string) - Required - The key to set. - **value** (TValue) - Required - The value to store. - **opts** (object) - Optional - Configuration options (get, ex, px, exat, pxat, keepTtl, nx, xx). ### Request Example { "key": "mykey", "value": "myvalue", "opts": { "ex": 60 } } ### Response #### Success Response (200) - **result** (string) - Returns "OK" or the old value if 'get' option is used. #### Response Example { "result": "OK" } ``` -------------------------------- ### ZCOUNT Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZCOUNT command in Upstash Redis with TypeScript. It first adds elements to a sorted set using ZADD and then uses ZCOUNT to retrieve the number of elements within a specified score range. The example shows filtering by excluding a score and including positive infinity. ```APIDOC ## ZCOUNT Command Example (TypeScript) ### Description Demonstrates how to use the ZCOUNT command in Upstash Redis with TypeScript. It first adds elements to a sorted set using ZADD and then uses ZCOUNT to retrieve the number of elements within a specified score range. The example shows filtering by excluding a score and including positive infinity. ### Method POST (Implicit via Redis Client) ### Endpoint (Not Applicable - Client-side command execution) ### Parameters (Refer to Upstash Redis documentation for ZCOUNT command parameters) ### Request Example ```typescript await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" }, ); const elements = await redis.zcount("key", "(1", "+inf"); console.log(elements); // 1 ``` ### Response #### Success Response - **count** (number) - The number of elements within the specified score range. #### Response Example ```json 1 ``` ``` -------------------------------- ### Redis Sorted Set Operations (ZADD/ZMSCORE) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates adding members to a sorted set and retrieving their scores using SDK methods. ```APIDOC ## ZADD and ZMSCORE Commands ### Description Adds members with their scores to a sorted set using `ZADD` and retrieves the scores of specified members using `ZMSCORE`. ### Method SDK Methods ### Endpoint N/A ### Parameters #### Request Body - **key** (string) - Required - The key of the sorted set. - **members** (array) - Required - List of objects containing score and member name. ### Request Example ```ts await redis.zadd("key", { score: 1, member: "m1" }, { score: 2, member: "m2" } ); const scores = await redis.zmscore("key", ["m2"]); ``` ### Response #### Success Response - **ZADD**: number of elements added. - **ZMSCORE**: (number | null)[] array of scores. ``` -------------------------------- ### Add Bull to Project Dependencies Source: https://upstash.com/docs/redis/overall/llms-txt Installs the Bull library, a Redis-based queue for Node.js, using npm. Bull is used for managing task queues in applications. ```shell npm install bull ``` -------------------------------- ### Implement multiple rate limits Source: https://upstash.com/docs/redis/sdks/ratelimit-py/features Shows how to apply different rate limiting policies to distinct user groups by initializing multiple Ratelimit instances with unique prefixes. ```python from upstash_ratelimit import Ratelimit, SlidingWindow from upstash_redis import Redis class MultiRL: def __init__(self) -> None: redis = Redis.from_env() self.free = Ratelimit( redis=redis, limiter=SlidingWindow(max_requests=10, window=10), prefix="ratelimit:free", ) self.paid = Ratelimit( redis=redis, limiter=SlidingWindow(max_requests=60, window=10), prefix="ratelimit:paid", ) # Create a new ratelimiter, that allows 10 requests per 10 seconds ratelimit = MultiRL() ratelimit.free.limit("userIP") ratelimit.paid.limit("userIP") ``` -------------------------------- ### Set Field Expiration in Hash Source: https://upstash.com/docs/redis/overall/llms-txt Sets an expiration time for a specific field within a Redis hash using the `hpexpireat` command. This example demonstrates using a timestamp in milliseconds and requires an initialized 'redis' client. ```APIDOC ## Set Field Expiration in Hash (hpexpireat) ### Description Sets an expiration time for a specific field within a Redis hash using a timestamp in milliseconds. ### Method hpexpireat ### Endpoint Not applicable (command-based) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Assuming 'redis' client is initialized await redis.hset("my-key", "my-field", "my-value"); const expirationSet = await redis.hpexpireat("my-key", "my-field", Date.now() + 1000); console.log(expirationSet); // Expected output: 1 (if successful) ``` ### Response #### Success Response (200) - **result** (integer) - Returns `1` if the timeout was set, `0` if the field or key does not exist. ``` -------------------------------- ### Deno Redis Client Initialization Source: https://upstash.com/docs/redis/overall/llms-txt Initializes the Upstash Redis client for Deno environments. ```APIDOC ## Client Initialization ### Description Initializes the Upstash Redis client for Deno environments, supporting explicit configuration or loading from environment variables. ### Method N/A ### Endpoint N/A ### Parameters #### Initialization Options - **url** (string) - Required (if not using `fromEnv`) - The URL of the Upstash Redis REST endpoint. - **token** (string) - Required (if not using `fromEnv`) - The access token for Upstash Redis. ### Request Example ```typescript import { Redis } from "https://deno.land/x/upstash_redis/mod.ts" const redis = new Redis({ url: "", token: "", }) ``` ``` -------------------------------- ### Get Random Key from Redis Database (API Reference) Source: https://upstash.com/docs/redis/overall/llms-txt Official API documentation for the Redis RANDOMKEY command. This command takes no arguments and returns a random key from the database. If the database is empty, it returns `None`. ```json { "command": "RANDOMKEY" } ``` -------------------------------- ### Create Phoenix App with No Ecto (Elixir) Source: https://upstash.com/docs/redis/overall/llms-txt Command to create a new Elixir Phoenix application without the Ecto ORM, as Redis will be used as the primary datastore. This simplifies setup when not requiring a relational database. ```APIDOC ## Create Phoenix App with No Ecto (Elixir) ### Description Initializes a new Elixir Phoenix project without including the Ecto ORM, suitable for projects using Redis as the primary data store. ### Command ```bash mix phx.new redix_demo --no-ecto ``` ### Parameters - **redix_demo**: The name of the new Phoenix application. - `--no-ecto`: Flag to exclude Ecto ORM from the project setup. ``` -------------------------------- ### Combine Sorted Sets with ZUNIONSTORE (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZUNIONSTORE command to create a new sorted set by merging multiple input sorted sets. Supports options for weights and aggregation methods like SUM, MIN, and MAX. ```typescript 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"]); console.log(res) // 2 ``` ```typescript 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 ``` ```typescript 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 ``` -------------------------------- ### Initialize SST Project and Dependencies Source: https://upstash.com/docs/redis/quickstarts/sst-v2 Commands to scaffold a new SST Next.js application and install the required Upstash Redis client package. ```shell npx create-sst@latest --template standard/nextjs cd my-sst-app npm install npm install @upstash/redis ``` -------------------------------- ### HVALS - Get All Hash Values (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves all values associated with fields in a hash stored at the specified key using the Upstash Redis Python client. If the key does not exist or is not a hash, an empty list is returned. ```python # Assuming 'redis' is an initialized Upstash Redis client redis.hset("myhash", values={"field1": "Hello", "field2": "World"}) response = redis.hvals("myhash") print(response) # Expected output: ['Hello', 'World'] ``` -------------------------------- ### Perform BITOP AND Operation in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Executes the BITOP command with the AND operation on source keys and stores the result in a destination key. ```APIDOC ## Perform BITOP AND Operation in TypeScript ### Description Executes the BITOP command with the AND operation on source keys and stores the result in a destination key. This example assumes a Redis client instance named 'redis' is available. ### Method TypeScript Code ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript await redis.bitop("AND", "destKey", "sourceKey1", "sourceKey2"); ``` ### Response #### Success Response - **result** (number) - The size of the string stored in the destination key. #### Response Example ```json 10 ``` ``` -------------------------------- ### Implement Redis counter in Django view Source: https://upstash.com/docs/redis/quickstarts/django Defines a view that connects to Redis using environment variables and increments a counter key on every request. ```python 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.') ``` -------------------------------- ### Routes with Different Rate Limit Algorithms (JSON) Source: https://upstash.com/docs/redis/integrations/ratelimit/strapi/configurations This configuration demonstrates applying different rate limiting strategies to specific routes. The '/api/restaurants/:id' route uses a fixed-window algorithm, while '/api/restaurants' uses a token bucket algorithm. Both identify users via the 'x-author' header. Requires UPSTASH_REDIS_REST_TOKEN and UPSTASH_REDIS_REST_URL environment variables. ```json { "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" } } } ``` -------------------------------- ### GET /xread API Endpoint Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Reads data from one or multiple streams starting from specified IDs. Supports reading new messages via the '$' identifier and limiting the number of returned messages. This is a conceptual API documentation. ```APIDOC ## GET /xread ### Description Reads data from one or multiple streams, starting from the specified IDs. Returns messages added to the stream after the provided ID. ### Method GET ### Endpoint /xread ### Parameters #### Request Body - **streams** (Dict[str, str]) - Required - A dictionary mapping stream keys to their starting IDs. Use `$` to read only new messages. - **count** (int) - Optional - The maximum number of messages to return per stream. ### Request Example { "streams": {"mystream": "0-0"}, "count": 1 } ### Response #### Success Response (200) - **data** (List[List[Any]]) - A list where each element represents a stream containing the stream key and a list of messages (ID and field-value pairs). #### Response Example [ ["mystream", [ ["1638360173533-0", ["field1", "value1", "field2", "value2"]], ["1638360173533-1", ["field1", "value3", "field2", "value4"]] ]] ] ``` -------------------------------- ### ZINTERSTORE Command Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Provides comprehensive documentation for the ZINTERSTORE command, which calculates the intersection of sets and stores the result in a new key. It details parameters like destination, keys, weights, aggregate function, and whether to include scores. ```json { "command": "ZINTERSTORE", "destination": "dest_set", "keys": ["key1", "key2"], "weights": [1.0, 0.5], "aggregate": "SUM", "withscores": false } ``` -------------------------------- ### Configure Upstash MCP via Claude CLI Source: https://upstash.com/docs/redis/integrations/mcp Commands to register the Upstash MCP server using the Claude CLI. These commands handle installation via npx and support both global and project-specific scopes. ```bash claude mcp add upstash -- npx -y @upstash/mcp-server@latest \ --email \ --api-key ``` ```bash claude mcp list ``` ```bash claude mcp add upstash --scope project -- npx -y @upstash/mcp-server@latest \ --email \ --api-key ``` -------------------------------- ### Fetch Stream Entries via REST API Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves entries from a Redis stream within a specified ID range. The endpoint accepts optional start, end, and count parameters to filter the returned stream data. ```http GET /stream/{key}?start=-&end=+&count=10 ``` -------------------------------- ### Configure Supabase Environment Variables Source: https://upstash.com/docs/redis/overall/llms-txt Copies a template environment file to the local configuration directory for a Supabase function. ```shell cp supabase/functions/upstash-redis-counter/.env.example supabase/functions/upstash-redis-counter/.env ``` -------------------------------- ### Initialize Upstash Redis Client in Vercel (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates initializing an Upstash Redis client in a Vercel application using `Redis.fromEnv()` in TypeScript. This method automatically reads connection details from environment variables. ```APIDOC ## Initialize Upstash Redis Client in Vercel (TypeScript) ### Description Demonstrates initializing an Upstash Redis client in a Vercel application using `Redis.fromEnv()` in TypeScript. This method automatically reads `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from environment variables for seamless connection and includes basic `set` and `get` operations. ### Method POST ### Endpoint (Not specified, typically part of a serverless function) ### Parameters (Environment variables: `UPSTASH_REDIS_REST_URL`, `UPSTASH_REDIS_REST_TOKEN`) ### Request Example ```typescript const { Redis } = require("@upstash/redis"); module.exports = async (req, res) => { const redis = Redis.fromEnv(); await redis.set("foo", "bar"); const bar = await redis.get("foo"); res.json({ body: `foo: ${bar}`, }); }; ``` ### Response #### Success Response (200) - **body** (string) - A message indicating the result of the set/get operation. #### Response Example ```json { "body": "foo: bar" } ``` ``` -------------------------------- ### Apply Rate Limit for All Routes (JSON) Source: https://upstash.com/docs/redis/overall/llms-txt Configuration to apply a fixed-window rate limit to all routes using UPSTASH_REDIS_REST_TOKEN and UPSTASH_REDIS_REST_URL. ```APIDOC ## Apply Rate Limit for All Routes ### Description Applies a fixed-window rate limit of 10 requests per 20 seconds to all routes, identifying users by their 'Authorization' header. ### Method N/A (Configuration) ### Endpoint N/A (Configuration) ### Parameters N/A (Configuration) ### Request Example ```json { "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":"header.Authorization", "limiter":{ "algorithm":"fixed-window", "tokens":10, "window":"20s" } } ], "prefix":"@strapi" } } } ``` ### Response N/A (Configuration) ``` -------------------------------- ### Flush All Keys in Upstash Redis (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Provides examples for clearing all keys from Upstash Redis using the FLUSHALL command in Python. It includes both synchronous and asynchronous options, with the ASYNC option allowing the operation to run in the background. ```python redis.flushall() ``` ```python redis.flushall(flush_type="ASYNC") ``` -------------------------------- ### Configure Upstash Redis environment variables Source: https://upstash.com/docs/redis/quickstarts/django Set the required REST URL and token as environment variables to allow the application to authenticate with the Upstash Redis database. ```shell export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ``` -------------------------------- ### Routes with Different Rate Limit Algorithms (JSON Configuration) Source: https://upstash.com/docs/redis/overall/llms-txt Configuration for setting distinct rate limits for different API routes using Upstash Redis. ```APIDOC ## Rate Limiting Configuration ### Description This configuration sets distinct rate limits for different API routes using Upstash Redis. It defines strategies for fixed-window and token bucket algorithms, specifying methods, paths, identifier sources, and limiter parameters. Requires UPSTASH_REDIS_REST_TOKEN and UPSTASH_REDIS_REST_URL environment variables. ### Method Configuration File (JSON) ### Endpoint N/A (Configuration) ### Parameters #### Configuration Fields - **strapi-plugin-upstash-ratelimit.enabled** (boolean) - Enables the plugin. - **strapi-plugin-upstash-ratelimit.resolve** (string) - Path to the plugin resolution. - **strapi-plugin-upstash-ratelimit.config.enabled** (boolean) - Enables the configuration. - **strapi-plugin-upstash-ratelimit.config.token** (string) - Upstash Redis REST Token (environment variable). - **strapi-plugin-upstash-ratelimit.config.url** (string) - Upstash Redis REST URL (environment variable). - **strapi-plugin-upstash-ratelimit.config.strategy** (array) - Array of rate limiting strategies. - **methods** (array) - HTTP methods to apply the strategy to. - **path** (string) - The API path. - **identifierSource** (string) - Source for identifying the client (e.g., header). - **limiter** (object) - Limiter configuration. - **algorithm** (string) - Rate limiting algorithm (e.g., 'fixed-window', 'tokenBucket'). - **tokens** (integer) - Number of tokens (for token bucket) or max requests (for fixed window). - **window** (string) - The time window for the rate limit. - **refillRate** (integer) - Rate at which tokens are refilled (for token bucket). - **strapi-plugin-upstash-ratelimit.config.prefix** (string) - Prefix for rate limit keys. ### Request Example ```json { "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" } } } ``` ### Response N/A (Configuration) ``` -------------------------------- ### POST /v2/redis/evalsha Source: https://upstash.com/docs/redis/overall/llms-txt Executes a pre-loaded Lua script on the Redis server using its SHA1 hash. ```APIDOC ## POST /v2/redis/evalsha ### Description Executes a Lua script in Redis using its SHA1 digest. ### Method POST ### Endpoint /v2/redis/evalsha ### Parameters #### Request Body - **sha1** (string) - Required - The SHA1 hash of the script. - **keys** (string[]) - Optional - Keys that the script will access. - **args** (any[]) - Optional - Arguments to pass to the script. ### Request Example { "sha1": "fb67a0c03b48ddbf8b4c9b011e779563bdbc28cb", "keys": [], "args": ["hello"] } ### Response #### Success Response (200) - **type** (any) - The result returned by the Lua script. ``` -------------------------------- ### Initialize and Add Sidekiq Gem Source: https://upstash.com/docs/redis/integrations/sidekiq This snippet demonstrates how to initialize a new Ruby project and add the Sidekiq gem using Bundler. This is the first step in setting up Sidekiq for your application. ```bash bundle init bundle add sidekiq ``` -------------------------------- ### SET and TYPE Commands Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to set a key-value pair and retrieve the data type of a key using the Upstash Redis client in TypeScript. ```APIDOC ## SET and TYPE Commands ### Description Sets a key-value pair and retrieves the data type of a key. ### Method SET, TYPE ### Endpoint SET /websites/upstash_redis TYPE /websites/upstash_redis ### Parameters #### Request Body (SET) - **key** (string) - Required - The key to set. - **value** (string) - Required - The value to set for the key. #### Query Parameters (TYPE) - **key** (string) - Required - The key whose type needs to be retrieved. ### Request Example (SET) ```typescript await redis.set("key", "value"); ``` ### Response (SET) #### Success Response (200) - **status** (string) - Indicates the success of the operation (e.g., "OK"). ### Response Example (SET) ```json { "status": "OK" } ``` ### Response (TYPE) #### Success Response (200) - **type** (string) - The data type of the key (e.g., "string", "hash", "list"). #### Response Example (TYPE) ```json "string" ``` ``` -------------------------------- ### Apply $boost to Prioritize and Demote Search Results (Redis CLI) Source: https://upstash.com/docs/redis/search/query-operators/boolean-operators/boost Provides examples of using the $boost operator within the Redis CLI for search queries. It demonstrates how to boost the relevance of items that are both 'wireless' and 'inStock', and how to demote 'budget' items. ```bash SEARCH.QUERY products '{"$":{"must":{"name":"headphones"},"$should":{"description":"wireless","inStock":true,"$boost":5.0}}}' SEARCH.QUERY products '{"$":{"must":{"category":"electronics"},"$should":{"description":"budget","$boost":-1.0}}}' ``` -------------------------------- ### Placeholder Python Code for Serverless API Source: https://upstash.com/docs/redis/overall/llms-txt A basic placeholder Python script intended for use in a serverless API, potentially with AWS Lambda and Upstash Redis. It serves as a structural example and does not contain specific Redis operations. ```python print("This is a placeholder for Python code.") ``` -------------------------------- ### Use Laravel Cache with Upstash Redis Source: https://upstash.com/docs/redis/overall/llms-txt Utilizes Laravel's Cache facade to put and get values, leveraging the configured Upstash Redis cache store. This example demonstrates storing a value with a 10-minute expiration time and retrieving it. ```php Cache::put('key', 'value', now()->addMinutes(10)); $value = Cache::get('key'); ``` -------------------------------- ### Export Redis Data using upstash-redis-dump Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates exporting data from a Redis instance using the `upstash-redis-dump` command-line tool. It requires specifying connection details like database number, host, port, password, and optionally TLS. ```shell upstash-redis-dump -db 0 -host eu1-moving-loon-6379.upstash.io -port 6379 -pass PASSWORD -tls > redis.dump ``` -------------------------------- ### Create an index with multiple prefixes Source: https://upstash.com/docs/redis/search/index-management Configures an index to monitor multiple key prefixes simultaneously. Ensure prefixes do not overlap or contain duplicates. ```TypeScript const articles = await redis.search.createIndex({ name: "articles", dataType: "json", prefix: ["article:", "blog:", "news:"], schema: s.object({ title: s.string(), body: s.string(), author: s.string().noStem(), publishedAt: s.date().fast(), viewCount: s.number(), }), }); ``` ```Python articles = redis.search.create_index( name="articles", data_type="json", prefix=["article:", "blog:", "news:"], schema={ "title": "TEXT", "body": "TEXT", "author": {"type": "TEXT", "nostem": True}, "publishedAt": {"type": "DATE", "fast": True}, "viewCount": "U64", }, ) ``` ```Redis CLI # String index with nested schema fields SEARCH.CREATE comments ON STRING PREFIX 1 comment: SCHEMA user.name TEXT user.email TEXT NOTOKENIZE comment TEXT upvotes U64 FAST commentedAt DATE FAST ``` -------------------------------- ### Increment Redis Key Value with INCRBY (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the INCRBY command in Upstash Redis to increment an integer value associated with a key. This example first sets an initial value and then increments it, showing the final result. ```typescript import { Redis } from '@upstash/redis'; const redis = new Redis({ url: process.env.UPSTASH_REDIS_URL, token: process.env.UPSTASH_REDIS_TOKEN, }); async function incrementValue() { try { await redis.set("key", 6); console.log("Initial value set to 6."); const result = await redis.incrby("key", 4); console.log(`Incremented by 4. New value: ${result}`); // returns 10 } catch (error) { console.error("Error incrementing value:", error); } } incrementValue(); ``` -------------------------------- ### Fetch Keys Matching Pattern (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Fetches all keys matching a given pattern using the KEYS command. This command can be blocking and has limitations on dataset size, recommending SCAN for production environments. ```python redis.keys("prefix*") redis.keys("*") ``` -------------------------------- ### Calculate and store set difference using Python Source: https://upstash.com/docs/redis/sdks/py/commands/set/sdiffstore This example demonstrates how to use the sdiffstore method in Python to compute the difference between two sets and store the result in a new key. It requires an active Redis connection and returns the count of elements in the resulting set. ```python redis.sadd("key1", "a", "b", "c") redis.sadd("key2", "c", "d", "e") # Store the result in a new set assert redis.sdiffstore("res", "key1", "key2") == 2 assert redis.smembers("set") == {"a", "b"} ``` -------------------------------- ### LRANGE Command API Documentation Source: https://upstash.com/docs/redis/overall/llms-txt Defines the LRANGE command, which returns specified elements of a list stored at a key. It details the required parameters (key, start, end indices) and the structure of its response, including type and description for each element. ```APIDOC ## LRANGE Command ### Description Returns the specified elements of the list stored at key. ### Method LRANGE ### Endpoint LRANGE ### Parameters #### Path Parameters - **key** (str) - Required - The key of the list. - **start** (int) - Required - The starting index of the range to return. Use negative numbers to specify offsets starting at the end of the list. - **end** (int) - Required - The ending index of the range to return. Use negative numbers to specify offsets starting at the end of the list. ### Response ``` -------------------------------- ### Remove and Retrieve First Element from JSON Array (Python) Source: https://upstash.com/docs/redis/overall/llms-txt This Python example uses `redis.json.arrpop` to remove and retrieve the first element from a JSON array by providing an explicit index of 0. It requires the key and JSON array path. ```python firstElement = redis.json.arrpop("key", "$.path.to.array", 0) ``` -------------------------------- ### Retrieve and delete key in Python Source: https://upstash.com/docs/redis/overall/llms-txt Uses the GETDEL command to fetch a value and immediately remove the key from the database. ```python redis.set("key", "value") assert redis.getdel("key") == "value" assert redis.get("key") == None ``` -------------------------------- ### Initialize Next.js project and install Upstash Redis Source: https://upstash.com/docs/redis/quickstarts/vercel-functions-app-router Commands to scaffold a new Next.js application and install the required @upstash/redis SDK dependency. ```shell npx create-next-app@latest cd my-app npm install @upstash/redis ``` -------------------------------- ### Initialize Django Project Source: https://upstash.com/docs/redis/quickstarts/vercel-python-runtime Commands to scaffold a new Django application using the Vercel template and navigate into the project directory. ```shell npx create-next-app vercel-django --example "https://github.com/vercel/examples/tree/main/python/django" cd vercel-django ``` -------------------------------- ### Sort and Paginate Products (TypeScript, Python, Redis CLI) Source: https://upstash.com/docs/redis/search/recipes/e-commerce-search Demonstrates how to sort product search results by price or rating and implement pagination using limit and offset. This is useful for handling large datasets efficiently. ```TypeScript const page1 = await products.query({ filter: { category: "Electronics > Audio > Headphones", }, orderBy: { rating: "DESC", }, limit: 20, }); const page2 = await products.query({ filter: { category: "Electronics > Audio > Headphones", }, orderBy: { rating: "DESC", }, limit: 20, offset: 20, }); const cheapest = await products.query({ filter: { name: "headphones", inStock: true, }, orderBy: { price: "ASC", }, limit: 10, }); ``` ```Python page1 = products.query( filter={"category": "Electronics > Audio > Headphones"}, order_by={"rating": "DESC"}, limit=20, ) page2 = products.query( filter={"category": "Electronics > Audio > Headphones"}, order_by={"rating": "DESC"}, limit=20, offset=20, ) cheapest = products.query( filter={"name": "headphones", "inStock": True}, order_by={"price": "ASC"}, limit=10, ) ``` ```Redis CLI SEARCH.QUERY products '{"category": "Electronics > Audio > Headphones"}' ORDERBY rating DESC LIMIT 20 SEARCH.QUERY products '{"category": "Electronics > Audio > Headphones"}' ORDERBY rating DESC LIMIT 20 OFFSET 20 SEARCH.QUERY products '{"name": "headphones", "inStock": true}' ORDERBY price ASC LIMIT 10 ``` -------------------------------- ### Perform Basic Redis Operations in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates setting a key-value pair and retrieving it using the Upstash Redis TypeScript client. Note that default responses may be base64 encoded. ```typescript await redis.set("key", "value"); const data = await redis.get("key"); console.log(data); ``` -------------------------------- ### Initialize AWS CDK Project and Dependencies Source: https://upstash.com/docs/redis/quickstarts/aws-lambda Commands to create a new CDK directory, initialize a TypeScript project, and install the required Upstash Redis SDK. ```shell mkdir counter-cdk && cd counter-cdk cdk init app --language typescript npm install @upstash/redis ``` -------------------------------- ### Calculate Set Difference with Upstash Redis (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt This TypeScript example demonstrates how to use the SDIFF command with Upstash Redis to find elements present in one set but not in others. It first adds elements to two sets and then calculates their difference. ```typescript await redis.sadd("set1", "a", "b", "c"); await redis.sadd("set2", "c", "d", "e"); const diff = await redis.sdiff("set1", "set2"); console.log(diff); ``` -------------------------------- ### Implement Redis Increment in Next.js Route Handler (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Creates a Next.js API route handler that uses Upstash Redis to increment a counter. It fetches credentials from environment variables and returns the updated count. This example is for the App Router. ```typescript 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' ``` -------------------------------- ### Find element index with LPOS in Python Source: https://upstash.com/docs/redis/sdks/py/commands/list/lpos Demonstrates how to use the LPOS command to find the index of a specific element in a list. Includes examples for basic matching, using rank to find specific occurrences, and using count to return multiple indices. ```python redis.rpush("key", "a", "b", "c"); assert redis.lpos("key", "b") == 1 ``` ```python redis.rpush("key", "a", "b", "c", "b"); assert redis.lpos("key", "b", rank=2) == 3 ``` ```python redis.rpush("key", "a", "b", "b") assert redis.lpos("key", "b", count=2) == [1, 2] ``` -------------------------------- ### Connect to Redis using redis-py Source: https://upstash.com/docs/redis/overall/llms-txt Establishes a connection to an Upstash Redis instance using the redis-py library. Requires SSL configuration for secure communication. ```python import redis r = redis.Redis( host= 'YOUR_ENDPOINT', port= 'YOUR_PORT', password= 'YOUR_PASSWORD', ssl=True) r.set('foo','bar') print(r.get('foo')) ``` -------------------------------- ### Push to list if exists using RPUSHX Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates the behavior of the RPUSHX command when the target list does not exist, returning 0. ```typescript const length = await redis.rpushx("key", "a"); console.log(length); ``` -------------------------------- ### POST /redis/v1/command (HSCAN) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates various ways to use the HSCAN command with Upstash Redis, including basic scanning, filtering by pattern, and limiting the number of returned fields. ```APIDOC ## HSCAN Command Usage Examples ### Description Demonstrates various ways to use the HSCAN command with Upstash Redis in TypeScript, including basic scanning, filtering by pattern, and limiting the number of returned fields. ### Method POST ### Endpoint /redis/v1/command ### Request Body - **command** (string) - Required - The command to execute (HSCAN) - **key** (string) - Required - The key to scan - **cursor** (number) - Required - The cursor position - **match** (string) - Optional - Pattern to filter results - **count** (number) - Optional - Number of elements to return ### Request Example { "command": "HSCAN", "key": "key", "cursor": 0 } ### Response #### Success Response (200) - **result** (array) - An array containing the next cursor and the list of fields/values #### Response Example { "result": [ "0", [ "id", 1, "username", "chronark", "name", "andreas" ] ] } ``` -------------------------------- ### XRANGE Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt API documentation for the XRANGE command, which returns stream entries matching a given range of IDs. ```APIDOC ## XRANGE Command API Reference ### Description Returns stream entries matching a given range of IDs. ### Method ``` XRANGE key start end [COUNT count] ``` ### Endpoint N/A (Command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```APIDOC XRANGE mystream - + COUNT 10 ``` ### Response #### Success Response (200) A map of stream entries, where each entry is keyed by its stream ID and contains a map of field-value pairs. #### Response Example ```json { "1678882602647-0": { "sensor-id": "1", "temperature": "25.5" }, "1678882603000-0": { "sensor-id": "2", "temperature": "26.1" } } ``` ``` -------------------------------- ### Set and Get Key Type in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to set a key-value pair and then retrieve its data type using the Upstash Redis client in TypeScript. The `set` command stores the value, and the `type` command returns the data type as a string. ```typescript await redis.set("key", "value"); const t = await redis.type("key"); console.log(t); // "string" ``` -------------------------------- ### Define Redis Command Requests in JSON Source: https://upstash.com/docs/redis/overall/llms-txt Provides example JSON payloads for Redis commands like SUNION and SCAN. These structures define the parameters required for executing specific operations via the REST API. ```json { "command": "SUNION", "keys": ["set1", "set2"] } ``` ```json { "cursor": "0", "match": "*", "count": 10, "type": "string" } ``` -------------------------------- ### Get Random Field and Value from Hash (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates fetching a random field along with its value from a Redis hash using the `hrandfield` command with the `withvalues` argument in Python. This returns a dictionary-like object containing one random field-value pair. ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hrandfield("myhash", count=1, withvalues=True) in [ {"field1": "Hello"}, {"field2": "World"} ] ``` -------------------------------- ### Set multiple keys via API Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the JSON request structure for setting multiple key-value pairs and the expected boolean response format. ```json { "key1": "value1", "key2": "value2" } ``` ```json { "result": true } ``` -------------------------------- ### Install @upstash/search-ioredis and ioredis Source: https://upstash.com/docs/redis/search/adapters/ioredis Install the necessary packages for using Redis Search with ioredis. This includes the adapter package and the ioredis client itself. ```bash npm install @upstash/search-ioredis ioredis ``` -------------------------------- ### Perform weighted sorted set intersection in Python Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to compute the intersection of multiple sorted sets using weights and SUM aggregation with the Python SDK. ```python 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)] ``` -------------------------------- ### Execute Python Script via CLI Source: https://upstash.com/docs/redis/overall/llms-txt Provides the standard command-line instruction to execute a Python script. Requires a local Python environment and the script file to be present in the working directory. ```bash python your_script_name.py ``` -------------------------------- ### Set Key-Value Pairs with Upstash Redis in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates basic key-value setting, setting expirations using the 'ex' option, and conditional updates using the 'xx' option with the Upstash Redis client. ```TypeScript await redis.set("my-key", {my: "value"}); await redis.set("my-key", {my: "value"}, { ex: 60 }); await redis.set("my-key", {my: "value"}, { xx: true }); ``` -------------------------------- ### Install Upstash Redis Client (Deno) Source: https://upstash.com/docs/redis/sdks/ts/getstarted Import the Upstash Redis client library directly in your Deno project. This is the primary method for Deno users. ```typescript import { Redis } from "https://deno.land/x/upstash_redis/mod.ts"; ``` -------------------------------- ### Connect to Upstash Redis (Node.js) Source: https://upstash.com/docs/redis/overall/llms-txt Connects to Upstash Redis using the ioredis library with a rediss connection string. Demonstrates setting and getting a key. Requires password, endpoint, and port. ```javascript 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); ``` -------------------------------- ### Configure Redis environment variables Source: https://upstash.com/docs/redis/quickstarts/nextjs-app-router Defines the required REST URL and token for the Upstash Redis instance within the .env file. ```bash UPSTASH_REDIS_REST_URL=https://holy-kite-17499.upstash.io UPSTASH_REDIS_REST_TOKEN=AURbAAIncDEyYjM4M... ``` -------------------------------- ### ZADD and ZLEXCOUNT Sorted Set Operations in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt This TypeScript example shows how to add elements to a Redis sorted set using `ZADD` and then count elements within a lexicographical range using `ZLEXCOUNT`. It requires the Upstash Redis client library. ```typescript await redis.zadd("key", { score: 1, member: "one"}, { score: 2, member: "two" }, ); const elements = await redis.zlexcount("key", "two", "+"); console.log(elements); // 1 ``` -------------------------------- ### Load Lua Library to Redis with TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Loads a Lua library into Redis using TypeScript. The library code must start with a shebang line specifying its name and use `redis.register_function` to expose functions. The `replace` option allows overwriting existing libraries. ```APIDOC ## Load Lua Library to Redis with TypeScript ### Description Loads a Lua library into Redis. The library code must start with a shebang line specifying its name and use `redis.register_function` to expose functions. The `replace` option allows overwriting existing libraries. ### Method POST ### Endpoint (Assumed Upstash Redis endpoint) ### Parameters * **code** (string) - Required - The Lua code for the library. * **replace** (boolean) - Optional - If true, overwrites an existing library with the same name. Defaults to false. ### Request Body ```json { "code": "#!lua name=mylib\n \n -- Simple function that returns a string\n redis.register_function(\n 'helloworld',\n function() return 'Hello World!' end\n )\n\n -- Complex function that modifies data with logic\n local function my_hset(keys, args) \n local hash = keys[1]\n local time = redis.call('TIME')[1]\n return redis.call('HSET', hash, '_last_modified_', time, unpack(args))\n end\n\n redis.register_function('my_hset', my_hset)\n ", "replace": true } ``` ### Request Example (TypeScript) ```typescript const code = `#!lua name=mylib -- Simple function that returns a string redis.register_function( 'helloworld', function() return 'Hello World!' end ) -- Complex function that modifies data with logic local function my_hset(keys, args) local hash = keys[1] local time = redis.call('TIME')[1] return redis.call('HSET', hash, '_last_modified_', time, unpack(args)) end redis.register_function('my_hset', my_hset) `; const libraryName = await redis.functions.load({ code, replace: true }); console.log(libraryName); // "mylib" ``` ### Response #### Success Response - **libraryName** (string) - The name of the loaded Lua library. ``` -------------------------------- ### Load Lua Library to Redis (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Loads a Lua library into Redis using TypeScript. The library code must start with a shebang line specifying its name and use `redis.register_function` to expose functions. The `replace` option allows overwriting existing libraries. ```typescript import { Redis } from '@upstash/redis'; const redis = new Redis({ url: process.env.UPSTASH_REDIS_URL, token: process.env.UPSTASH_REDIS_TOKEN, }); const code = `#!lua name=mylib -- Simple function that returns a string redis.register_function( 'helloworld', function() return 'Hello World!' end ) -- Complex function that modifies data with logic local function my_hset(keys, args) local hash = keys[1] local time = redis.call('TIME')[1] return redis.call('HSET', hash, '_last_modified_', time, unpack(args)) end redis.register_function('my_hset', my_hset) `; async function loadLibrary() { try { const libraryName = await redis.functions.load({ code, replace: true }); console.log(`Successfully loaded library: ${libraryName}`); // "mylib" } catch (error) { console.error("Error loading library:", error); } } loadLibrary(); ``` -------------------------------- ### Create React App for Notification API Source: https://upstash.com/docs/redis/tutorials/notification Sets up a new React application using create-react-app. This is the initial step for building the client-side of the serverless notification system. ```shell npx create-react-app serverless-notification-api ``` -------------------------------- ### Set Client Library Metadata using Python Source: https://upstash.com/docs/redis/sdks/py/commands/connection/client_setinfo Demonstrates how to use the client_setinfo method to define library names and versions. This command is case-insensitive and helps in identifying specific client instances in Redis monitoring tools. ```python # Set the library name result = redis.client_setinfo("LIB-NAME", "redis-py") assert result == "OK" # Set the library version result = redis.client_setinfo("LIB-VER", "1.0.0") assert result == "OK" # Attributes are case-insensitive redis.client_setinfo("lib-name", "redis-py") redis.client_setinfo("lib-ver", "2.0.0") # Common pattern: include wrapper or framework info redis.client_setinfo("LIB-NAME", "redis-py(upstash_v1.0.0)") redis.client_setinfo("LIB-VER", "1.0.0") # Set both library name and version redis.client_setinfo("LIB-NAME", "my-redis-wrapper") redis.client_setinfo("LIB-VER", "3.2.1") ``` -------------------------------- ### Clear JSON Data in Upstash Redis (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to clear JSON data stored in Upstash Redis using the `redis.json.clear` command in Python. Examples include clearing an entire JSON document and clearing a specific path within a JSON document. ```python redis.json.clear("key") ``` ```python redis.json.clear("key", "$.my.key") ``` -------------------------------- ### Implement Rate Limiting with blockUntilReady (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates using `ratelimit.blockUntilReady` to create a rate limiter and wait for a request to be allowed. It handles initialization and the success or failure of the `blockUntilReady` call within a specified timeout. ```typescript // 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, }); // `blockUntilReady` returns a promise that resolves as soon as the request is allowed to be processed, or after 30 seconds const { success } = await ratelimit.blockUntilReady("id", 30_000); if (!success) { return "Unable to process, even after 30 seconds"; } doExpensiveCalculation(); return "Here you go!"; ``` -------------------------------- ### Create New Laravel Project Source: https://upstash.com/docs/redis/tutorials/laravel_caching Initializes a new Laravel project named 'todo-cache' and navigates into the project directory. This is the first step in setting up the application. ```shell laravel new todo-cache cd todo-cache ``` -------------------------------- ### Get Length of Redis List (LLEN Command API Reference) Source: https://upstash.com/docs/redis/overall/llms-txt API documentation for the Redis LLEN command. This command takes a key as a string argument and returns the number of elements in the list associated with that key. The response is a number representing the list's length. ```json { "command": "LLEN", "arguments": { "key": { "type": "string", "required": true, "description": "The key of the list." } }, "response": { "type": "number", "required": true, "description": "The length of the list at key." } } ``` -------------------------------- ### Create Phoenix App without Ecto (Elixir) Source: https://upstash.com/docs/redis/overall/llms-txt Command to create a new Elixir Phoenix application without the Ecto ORM, suitable for projects where Redis serves as the primary datastore. ```bash mix phx.new redix_demo --no-ecto ``` -------------------------------- ### RPUSH Command Example (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the RPUSH command to add elements to the end of a list in Upstash Redis. This function takes a key and one or more elements as input and returns the new length of the list after the operation. Ensure you have the Upstash Redis client initialized. ```APIDOC ## RPUSH Command Example (TypeScript) ### Description Demonstrates how to use the RPUSH command to add elements to the end of a list in Upstash Redis. This function takes a key and one or more elements as input and returns the new length of the list after the operation. Ensure you have the Upstash Redis client initialized. ### Method SDK Method ### Endpoint N/A (SDK Method) ### Parameters #### Query Parameters - **key** (string) - Required - The key of the list. - **elements** (...string) - Required - One or more elements to add to the list. ### Request Example ```typescript const length1 = await redis.rpush("key", "a", "b", "c"); console.log(length1); // 3 const length2 = await redis.rpush("key", "d"); console.log(length2); // 4 ``` ### Response #### Success Response (200) - **length** (number) - The new length of the list after adding the elements. ``` -------------------------------- ### Initialize and Use Upstash Redis in Next.js Source: https://upstash.com/docs/redis/howto/vercelintegration Demonstrates how to initialize the Upstash Redis client using environment variables and perform basic set/get operations within a Next.js API route handler. ```typescript import { Redis } from "@upstash/redis"; import { type NextRequest, NextResponse } from "next/server"; const redis = Redis.fromEnv(); export const POST = async (request: NextRequest) => { await redis.set("foo", "bar"); const bar = await redis.get("foo"); return NextResponse.json({ body: `foo: ${bar}`, }); } ``` -------------------------------- ### Increment Bitfield Values with Python Source: https://upstash.com/docs/redis/overall/llms-txt Provides a Python example for incrementing unsigned integer values within a Redis bitfield using the `bitfield` command's `incr` method. It shows how to initialize a bitfield key and perform multiple increments, returning the values before each operation. ```python import redis r = redis.Redis(url="YOUR_REDIS_URL") r.set('my-bitfield-key', '') # Initialize or clear the key # Increment offset 0 by 16 (unsigned 4-bit integer) # Increment offset 4 by 1 (unsigned 4-bit integer) result = r.bitfield('my-bitfield-key') \ .incr('u4', 0, 16) \ .incr('u4', 4, 1) \ .execute() print(f"Result: {result}") # Expected: [0, 0] ``` -------------------------------- ### Get Multiple Hash Fields with HMGET (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates retrieving multiple fields from a hash in Upstash Redis using the HMGET command in Python. It first sets a hash with sample data using HSET and then retrieves specified fields, asserting the expected output. ```python redis.hset("myhash", values={ "field1": "Hello", "field2": "World" }) assert redis.hmget("myhash", "field1", "field2") == ["Hello", "World"] ``` -------------------------------- ### Subscribe to Channels by Patterns with PSUBSCRIBE in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the PSUBSCRIBE command to listen for messages on Redis channels matching a specific pattern. It requires the Upstash Redis client and handles incoming messages via event listeners. ```typescript const subscription = redis.psubscribe(["user:*"]); const messages = []; subscription.on("pmessage", (data) => { messages.push(data.message); }); await redis.publish("user:123", "user:123 message"); await redis.publish("user:456", "user:456 message"); await redis.publish("other:789", "other:789 message"); console.log(messages[0]) console.log(messages[1]) console.log(messages[2]) ``` -------------------------------- ### Check Current Notification Configuration (redis-cli) Source: https://upstash.com/docs/redis/howto/keyspacenotifications This example demonstrates how to check the current keyspace and keyevent notification configuration using redis-cli. It connects to the Redis instance and executes the 'config get' command for 'notify-keyspace-events'. ```bash redis-cli --tls -u $UPSTASH_REDIS_CLI_URL config get notify-keyspace-events ``` -------------------------------- ### Python Bitmap Operations (SETBIT and BITPOS) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates bit manipulation using SETBIT to set bits and BITPOS to find the position of specific bit values within a range. ```python original_bit = redis.setbit(key, 4, 1) ``` ```python redis.setbit("mykey", 7, 1) redis.setbit("mykey", 8, 1) assert redis.bitpos("mykey", 1) == 7 assert redis.bitpos("mykey", 0) == 0 # With a range assert redis.bitpos("mykey", 1, 0, 2) == 0 assert redis.bitpos("mykey", 1, 2, 3) == -1 ``` ```python redis.bitpos("key", 1, 5, 20) ``` -------------------------------- ### Redis ZINTER Aggregation with Python Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates how to use the ZINTER command in Upstash Redis with Python to calculate the aggregated intersection of sets. This example includes scores and uses the SUM aggregation. ```python redis.zadd("key1", {"a": 1, "b": 2, "c": 3}) redis.zadd("key2", {"a": 3, "b": 4, "c": 5}) result = redis.zunion(["key1", "key2"], withscores=True, aggregate="SUM") assert result == [("a", 4), ("b", 6), ("c", 8)] ``` -------------------------------- ### Redis Pipelining in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Shows how to use the pipeline feature in Upstash Redis with TypeScript to send multiple commands in a single HTTP request. Pipelining allows for efficient batching of commands but does not guarantee atomic execution. ```APIDOC ## Redis Pipelining ### Description Executes multiple Redis commands in a single request using pipelining. This improves performance by reducing network latency. ### Method PIPELINE ### Endpoint /websites/upstash_redis/pipeline ### Parameters #### Request Body - **commands** (Array) - Required - An array of commands to be executed in the pipeline. Each object should specify the command and its arguments. ### Request Example ```typescript const p = redis.pipeline(); p.set("key", 2); p.incr("key"); p.hset("key2", "field", { hello: "world" }).hvals("key2"); const res = await p.exec<[string, number, string[]]>(); ``` ### Response #### Success Response (200) - **results** (Array) - An array containing the results of each command executed in the pipeline, in the order they were added. #### Response Example ```json ["OK", 3, "world"] ``` ``` -------------------------------- ### Initialize AWS CDK Project with TypeScript Source: https://upstash.com/docs/redis/tutorials/pythonapi Initializes a new AWS CDK project with TypeScript as the language. This command sets up the basic project structure and configuration files for a CDK application. ```shell cdk init app --language typescript ``` -------------------------------- ### Set Redis Key with Options Source: https://upstash.com/docs/redis/overall/llms-txt Configures the SET command for Redis, supporting expiration, conditional updates (NX/XX), and retrieval of previous values. Non-string values are automatically stringified. ```json { "key": "mykey", "value": "myvalue", "opts": { "ex": 60, "nx": true } } ``` -------------------------------- ### Dockerfile for Node.js Application Source: https://upstash.com/docs/redis/quickstarts/koyeb Defines the steps to build a Docker image for a Node.js application, including installing dependencies, copying application code, and setting runtime configurations. It uses multi-stage builds for optimization. ```dockerfile FROM node:18-alpine AS base FROM base AS deps RUN apk add --no-cache libc6-compat WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci FROM base AS runner WORKDIR /app RUN addgroup --system --gid 1001 nodejs RUN adduser --system --uid 1001 nodejs COPY --from=deps /app/node_modules ./ COPY . . USER node EXPOSE 3000 ENV PORT 3000 CMD ["npm", "run", "start"] ``` -------------------------------- ### Set JSON Value with NX/XX Options (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates setting JSON values in Redis using `redis.json.set` in TypeScript. It covers basic usage and conditional setting with `NX` (set if not exists) and `XX` (set if exists) options, providing examples for request and success responses. ```json { "key": "mykey", "path": ".$.path", "value": {"nested": "data"}, "options": {"nx": true} } ``` -------------------------------- ### Initialize Redis Sorted Set for Auto-complete Source: https://upstash.com/docs/redis/overall/llms-txt Populates a Redis Sorted Set with country names and their generated prefixes. This script iterates through a dataset to enable efficient prefix-based searching in Redis. ```javascript require('dotenv').config() var Redis = require("ioredis"); var countries = [ {"name": "Afghanistan", "code": "AF"}, {"name": "Albania", "code": "AL"} ] 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) })(); } ``` -------------------------------- ### Perform ZINTERSTORE operations with Upstash Redis Source: https://upstash.com/docs/redis/sdks/ts/commands/zset/zinterstore Demonstrates how to use the ZINTERSTORE command to intersect sorted sets. Includes examples for basic intersection, applying weights to keys, and using aggregation methods. ```typescript 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 ``` ```typescript 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 ``` ```typescript 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 ``` -------------------------------- ### Retrieve Stream Entries with XRANGE Command Source: https://upstash.com/docs/redis/overall/llms-txt API reference for the Redis XRANGE command, which returns stream entries within a specified range of IDs. It takes the stream key, start and end IDs, and an optional count. The response is a map of stream entries keyed by their IDs. ```redis XRANGE mystream - + COUNT 10 ``` -------------------------------- ### Initialize Multi-Region Rate Limiter in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Configures a MultiRegionRatelimit instance using multiple Redis regions. It demonstrates setting up the sliding window algorithm and enabling analytics for tracking. ```typescript import { MultiRegionRatelimit } from "@upstash/ratelimit"; import { Redis } from "@upstash/redis"; const ratelimit = new MultiRegionRatelimit({ redis: [ new Redis({}), new Redis({}), new Redis({}) ], limiter: MultiRegionRatelimit.slidingWindow(10, "10 s"), analytics: true, }); const identifier = "api"; const { success } = await ratelimit.limit(identifier); ``` -------------------------------- ### Node.js Express App with Redis Integration Source: https://upstash.com/docs/redis/overall/llms-txt Sets up a basic Express.js server using Upstash Redis to store and retrieve a visitor counter. It connects via an environment variable and implements asynchronous GET and SET operations. Ensure REDIS_URL is set. ```javascript 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}`)); ``` -------------------------------- ### Python Example: Insert into Redis List using LINSERT Source: https://upstash.com/docs/redis/sdks/py/commands/list/linsert This Python snippet demonstrates how to use the LINSERT command to insert an element into a Redis list. It first populates a list and then inserts a new value 'x' before the element 'b'. Ensure you have a Redis client library (like `redis-py`) installed and configured to connect to your Upstash Redis instance. ```python import redis # Assuming 'redis' is an initialized Redis client instance connected to Upstash # redis = redis.Redis(host='YOUR_UPSTASH_HOST', port=YOUR_UPSTASH_PORT, password='YOUR_UPSTASH_PASSWORD') # Example usage: redis.rpush("key", "a", "b", "c") # The list 'key' now contains: ["a", "b", "c"] # Insert 'x' before 'b' result = redis.linsert("key", "before", "b", "x") # The list 'key' now contains: ["a", "x", "b", "c"] # 'result' will be the new length of the list (4 in this case) print(f"List length after insertion: {result}") # Example of inserting after a pivot that doesn't exist: result_not_found = redis.linsert("key", "after", "z", "y") # 'result_not_found' will be -1 print(f"Result when pivot not found: {result_not_found}") ``` -------------------------------- ### Load Redis Library with Lua Code Source: https://upstash.com/docs/redis/overall/llms-txt Loads a Lua library into Redis using the `functions.load` method. The library must start with `#!lua name=` and register functions using `redis.register_function`. The `replace` option allows overwriting existing libraries. ```typescript const code = `#!lua name=mylib -- Simple function that returns a string redis.register_function( 'helloworld', function() return 'Hello World!' end ) -- Complex function that modifies data with logic local function my_hset(keys, args) local hash = keys[1] local time = redis.call('TIME')[1] return redis.call('HSET', hash, '_last_modified_', time, unpack(args)) end redis.register_function('my_hset', my_hset) `; const libraryName = await redis.functions.load({ code, replace: true }); console.log(libraryName); // "mylib" ``` -------------------------------- ### Perform XAUTOCLAIM Operation in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates a basic XAUTOCLAIM operation in TypeScript to transfer pending messages from a stream. It requires the stream key, consumer group name, new consumer name, minimum idle time, and starting stream entry ID. The result includes pagination information and claimed/deleted message data. ```typescript const result = await redis.xautoclaim( "mystream", "mygroup", "consumer1", 60000, "0-0" ); ``` -------------------------------- ### Perform BITOP AND Operation in TypeScript Source: https://upstash.com/docs/redis/overall/llms-txt Executes the `BITOP` command with the `AND` operation on source keys and stores the result in a destination key using the Upstash Redis client in TypeScript. Assumes a Redis client instance named 'redis' is available. ```typescript await redis.bitop("AND", "destKey", "sourceKey1", "sourceKey2"); ``` -------------------------------- ### UNLINK /api/redis/unlink Source: https://upstash.com/docs/redis/overall/llms-txt Delete one or more keys. ```APIDOC ## UNLINK /api/redis/unlink ### Description Delete one or more keys. ### Method UNLINK ### Endpoint /api/redis/unlink ### Parameters #### Path Parameters - **key** (string) - Required - The key to delete. - **keys** (string[]) - Optional - Multiple keys to delete. ### Request Example ```json { "key": "mykey" } ``` ### Response #### Success Response (200) - **count** (integer) - The number of keys deleted. #### Response Example ```json { "count": 1 } ``` ``` -------------------------------- ### PERSIST /api/redis/persist Source: https://upstash.com/docs/redis/overall/llms-txt Remove the expiration from a key. ```APIDOC ## PERSIST /api/redis/persist ### Description Remove the expiration from a key. ### Method PERSIST ### Endpoint /api/redis/persist ### Parameters #### Path Parameters - **key** (string) - Required - The key to remove expiration from. ### Request Example { "key": "mykey" } ### Response #### Success Response (200) - **removed** (integer) - 1 if the expiration was removed, 0 otherwise. #### Response Example { "removed": 1 } ``` -------------------------------- ### Insert Sample Article Data into Redis Source: https://upstash.com/docs/redis/search/recipes/blog-search Demonstrates how to store article metadata and content in Redis hashes. This pattern is commonly used to prepare datasets for full-text search indexing. ```TypeScript await redis.hset("article:1", { title: "Getting Started with Redis Search", body: "Redis Search provides powerful full-text search capabilities directly in Redis. In this tutorial, we'll explore how to create indexes, define schemas, and write queries. Full-text search allows you to find documents based on their content rather than just their keys. This is essential for building search features in modern applications.", summary: "Learn how to add full-text search to your Redis application with practical examples.", author: "Jane Smith", tags: "redis,search,tutorial", publishedAt: "2024-03-15T10:00:00Z", updatedAt: "2024-03-15T10:00:00Z", published: "true", viewCount: "1542", }); await redis.hset("article:2", { title: "Advanced Query Techniques for Search", body: "Once you've mastered the basics, it's time to explore advanced query techniques. Boolean operators let you combine conditions with AND, OR, and NOT logic. Phrase matching ensures words appear in sequence. Fuzzy matching handles typos gracefully. Together, these features enable sophisticated search experiences.", summary: "Master boolean operators, phrase matching, and fuzzy search for better results.", author: "John Doe", tags: "redis,search,advanced", publishedAt: "2024-03-20T14:30:00Z", updatedAt: "2024-03-22T09:15:00Z", published: "true", viewCount: "892", }); await redis.hset("article:3", { title: "Building Real-Time Search with Redis", body: "Real-time search requires instant indexing and low-latency queries. Redis excels at both. When you write data to Redis, the search index updates automatically. Queries execute in milliseconds, even with millions of documents. This makes Redis ideal for applications where search results must reflect the latest data.", summary: "Build search features that update instantly as data changes.", author: "Jane Smith", tags: "redis,real-time,performance", publishedAt: "2024-03-25T08:00:00Z", updatedAt: "2024-03-25T08:00:00Z", published: "true", viewCount: "2103", }); ``` ```Python redis.hset("article:1", { "title": "Getting Started with Redis Search", "body": "Redis Search provides powerful full-text search capabilities directly in Redis. In this tutorial, we'll explore how to create indexes, define schemas, and write queries. Full-text search allows you to find documents based on their content rather than just their keys. This is essential for building search features in modern applications.", "summary": "Learn how to add full-text search to your Redis application with practical examples.", "author": "Jane Smith", "tags": "redis,search,tutorial", "publishedAt": "2024-03-15T10:00:00Z", "updatedAt": "2024-03-15T10:00:00Z", "published": "true", "viewCount": "1542", }) redis.hset("article:2", { "title": "Advanced Query Techniques for Search", "body": "Once you've mastered the basics, it's time to explore advanced query techniques. Boolean operators let you combine conditions with AND, OR, and NOT logic. Phrase matching ensures words appear in sequence. Fuzzy matching handles typos gracefully. Together, these features enable sophisticated search experiences.", "summary": "Master boolean operators, phrase matching, and fuzzy search for better results.", "author": "John Doe", "tags": "redis,search,advanced", "publishedAt": "2024-03-20T14:30:00Z", "updatedAt": "2024-03-22T09:15:00Z", "published": "true", "viewCount": "892", }) redis.hset("article:3", { "title": "Building Real-Time Search with Redis", "body": "Real-time search requires instant indexing and low-latency queries. Redis excels at both. When you write data to Redis, the search index updates automatically. Queries execute in milliseconds, even with millions of documents. This makes Redis ideal for applications where search results must reflect the latest data.", "summary": "Build search features that update instantly as data changes.", "author": "Jane Smith", "tags": "redis,real-time,performance", "publishedAt": "2024-03-25T08:00:00Z", "updatedAt": "2024-03-25T08:00:00Z", "published": "true", "viewCount": "2103", }) ``` -------------------------------- ### Configure Environment and Deploy Source: https://upstash.com/docs/redis/quickstarts/aws-lambda Commands to export necessary Redis credentials and execute the CDK deployment lifecycle. ```shell export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= cdk synth cdk bootstrap cdk deploy ``` -------------------------------- ### Install Python Libraries for Chat App Source: https://upstash.com/docs/redis/tutorials/python_realtime_chat Installs Flask, Flask-SocketIO, and the Redis library using pip. These are essential dependencies for building the real-time chat application. ```bash pip install flask flask-socketio redis ``` -------------------------------- ### Initialize Redis Data with RPUSH Source: https://upstash.com/docs/redis/overall/llms-txt Populates the Redis database with a list of coin objects using the RPUSH command via Redis CLI. Each argument to RPUSH is a value to be added to the list. ```shell rpush coins '{ "name" : "Bitcoin", "price": 56819, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/1.png"}' '{ "name" : "Ethereum", "price": 2130, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/1027.png"}' '{ "name" : "Cardano", "price": 1.2, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/2010.png"}' '{ "name" : "Polkadot", "price": 35.96, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/6636.png"}' '{ "name" : "Stellar", "price": 0.506, "image": "https://s2.coinmarketcap.com/static/img/coins/64x64/512.png"} ``` -------------------------------- ### Flask App Setup with Socket.IO and Redis Source: https://upstash.com/docs/redis/tutorials/python_realtime_chat Initializes a Flask application, configures a secret key, sets up a secure Redis connection using TLS, and integrates Socket.IO with Redis as the message queue. It defines WebSocket event handlers for connection, disconnection, and message broadcasting. ```python from flask import Flask, render_template from flask_socketio import SocketIO, emit import os app = Flask(__name__) app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", "a_default_secret_key") # Configure Redis URL with TLS for secure communication redis_url = os.environ.get("REDIS_URL", "redis://localhost:6379/0") socketio = SocketIO(app, message_queue=redis_url, logger=True, engineio_logger=True) @socketio.on("connect") def handle_connect(): print("Client connected") emit("message", {"user": "System", "message": "Welcome to the chat!"}) @socketio.on("disconnect") def handle_disconnect(): print("Client disconnected") @socketio.on("message") def handle_message(data): print(f"Received message: {data}") # Broadcast message to all clients except the sender emit("message", data, broadcast=True, include_self=False) @app.route("/") def index(): return render_template("chat.html") if __name__ == "__main__": socketio.run(app, debug=True, host='0.0.0.0', port=5000) ``` -------------------------------- ### Load Redis Library with Lua Code Source: https://upstash.com/docs/redis/sdks/ts/commands/functions/load Loads a Lua library into Redis. The library must start with `#!lua name=` and register functions using `redis.register_function`. The `replace` option allows overwriting existing libraries. This example demonstrates loading a simple 'helloworld' function and a more complex 'my_hset' function. ```typescript const code = `#!lua name=mylib -- Simple function that returns a string redis.register_function( 'helloworld', function() return 'Hello World!' end ) -- Complex function that modifies data with logic local function my_hset(keys, args) local hash = keys[1] local time = redis.call('TIME')[1] return redis.call('HSET', hash, '_last_modified_', time, unpack(args)) end redis.register_function('my_hset', my_hset) `; const libraryName = await redis.functions.load({ code, replace: true }); console.log(libraryName); // "mylib" ``` -------------------------------- ### TYPE /api/redis/type Source: https://upstash.com/docs/redis/overall/llms-txt Determine the type stored at key. ```APIDOC ## TYPE /api/redis/type ### Description Determine the type stored at key. ### Method TYPE ### Endpoint /api/redis/type ### Parameters #### Path Parameters - **key** (string) - Required - The key to determine the type of. ### Request Example ```json { "key": "mykey" } ``` ### Response #### Success Response (200) - **type** (string) - The type of the key (e.g., "string", "list", "hash", "set", "zset", "stream", "none"). #### Response Example ```json { "type": "string" } ``` ``` -------------------------------- ### Find bit position using BITPOS in Python Source: https://upstash.com/docs/redis/sdks/py/commands/bitmap/bitpos Demonstrates how to use the BITPOS command to locate bits in a Redis key. Includes examples of basic usage and range-restricted searches. ```python redis.setbit("mykey", 7, 1) redis.setbit("mykey", 8, 1) assert redis.bitpos("mykey", 1) == 7 assert redis.bitpos("mykey", 0) == 0 # With a range assert redis.bitpos("mykey", 1, 0, 2) == 0 assert redis.bitpos("mykey", 1, 2, 3) == -1 ``` ```python redis.bitpos("key", 1, 5, 20) ``` -------------------------------- ### Create Product Index (Redis CLI) Source: https://upstash.com/docs/redis/search/recipes/e-commerce-search Provides the Redis CLI command to create a search index for products. This command defines the index name, data type, key prefix, and the schema for various fields. ```APIDOC ## SEARCH.CREATE products ### Description Uses the Redis CLI command `SEARCH.CREATE` to establish a search index named 'products'. It specifies the index type as JSON, sets a key prefix of 'product:', and defines the schema for fields including text, numeric, boolean, and date types with specific attributes like NOSTEM, NOTOKENIZE, and FAST. ### Method CLI Command ### Endpoint N/A (Redis CLI) ### Parameters - **products** (string) - Required - The name of the index to create. - **ON JSON** - Required - Specifies that the index operates on JSON documents. - **PREFIX 1 product:** - Required - Sets the key prefix for documents in this index. - **SCHEMA** - Required - Defines the fields and their types within the index schema: - **name TEXT** - Full-text searchable string. - **description TEXT** - Full-text searchable string. - **brand TEXT NOSTEM** - Text string, prevents stemming. - **category TEXT NOTOKENIZE** - Text string, treats the entire string as a single token. - **price F64 FAST** - Floating-point number, enables fast sorting. - **rating F64 FAST** - Floating-point number, enables fast sorting. - **reviewCount U64** - Unsigned 64-bit integer. - **inStock BOOL** - Boolean field. - **createdAt DATE FAST** - Date field, enables fast indexing. ### Request Example ```bash SEARCH.CREATE products ON JSON PREFIX 1 product: SCHEMA name TEXT description TEXT brand TEXT NOSTEM category TEXT NOTOKENIZE price F64 FAST rating F64 FAST reviewCount U64 inStock BOOL createdAt DATE FAST ``` ### Response #### Success Response (200) - (No specific response body, command execution indicates success or failure) #### Response Example (Command execution output in the Redis CLI) ``` -------------------------------- ### POST /v2/redis/scard Source: https://upstash.com/docs/redis/overall/llms-txt Returns the number of members in a set. ```APIDOC ## POST /v2/redis/scard ### Description Returns the number of members in a set. ### Method POST ### Endpoint /v2/redis/scard ### Parameters #### Query Parameters - **key** (string) - Required - The key of the set. ### Request Body This endpoint does not require a request body. ### Response #### Success Response (200) - **value** (number) - How many members are in the set. #### Response Example ```json { "value": 3 } ``` ``` -------------------------------- ### Deploy Serverless Functions Source: https://upstash.com/docs/redis/tutorials/histogram Uses the Serverless Framework to deploy functions to the cloud environment. This command initializes the infrastructure required for the API endpoints. ```bash serverless deploy ``` -------------------------------- ### Run Nuxt Development Server and Test Endpoint Source: https://upstash.com/docs/redis/tutorials/nuxtjs_with_redis Starts the Nuxt development server to run the application locally. Once the server is running, you can test the defined API endpoint by making a `curl` request to `http://localhost:3000/api/increment`. The response will show the success status, the current call count, and the last time the endpoint was called. ```bash npm run dev # To test the endpoint: curl http://localhost:3000/api/increment ``` -------------------------------- ### RENAMENX /api/redis/renamenx Source: https://upstash.com/docs/redis/overall/llms-txt Rename a key, only if the new key does not exist. ```APIDOC ## RENAMENX /api/redis/renamenx ### Description Rename a key, only if the new key does not exist. ### Method RENAMENX ### Endpoint /api/redis/renamenx ### Parameters #### Path Parameters - **oldKey** (string) - Required - The current name of the key. - **newKey** (string) - Required - The new name for the key. ### Request Example { "oldKey": "mykey", "newKey": "newkey" } ### Response #### Success Response (200) - **renamed** (integer) - 1 if the key was renamed, 0 if the new key already exists. #### Response Example { "renamed": 1 } ``` -------------------------------- ### Install Upstash Ratelimit Plugin for Strapi Source: https://upstash.com/docs/redis/integrations/ratelimit/strapi/getting-started Commands to install the Upstash Ratelimit plugin using npm or yarn package managers. ```bash npm install --save @upstash/strapi-plugin-upstash-ratelimit ``` ```bash yarn add @upstash/strapi-plugin-upstash-ratelimit ``` -------------------------------- ### EXPIRE /api/redis/expire Source: https://upstash.com/docs/redis/overall/llms-txt Sets a time-to-live (TTL) for a key in seconds. ```APIDOC ## EXPIRE /api/redis/expire ### Description Set a key's time to live in seconds. ### Method EXPIRE ### Endpoint /api/redis/expire ### Parameters #### Path Parameters - **key** (string) - Required - The key to set expiration for. - **seconds** (integer) - Required - The time to live in seconds. ### Request Example { "key": "mykey", "seconds": 60 } ### Response #### Success Response (200) - **success** (boolean) - True if the expiration was set successfully. #### Response Example { "success": true } ``` -------------------------------- ### Perform ZUNIONSTORE operations in Python Source: https://upstash.com/docs/redis/sdks/py/commands/zset/zunionstore Demonstrates how to use the ZUNIONSTORE command to combine sorted sets. Examples cover basic union, aggregation using SUM, and applying weights to the input sets. ```python 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 ``` ```python 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)] ``` ```python 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)] ``` -------------------------------- ### EXISTS /api/redis/exists Source: https://upstash.com/docs/redis/overall/llms-txt Checks for the existence of a specific key in the database. ```APIDOC ## EXISTS /api/redis/exists ### Description Determine if a key exists. ### Method EXISTS ### Endpoint /api/redis/exists ### Parameters #### Path Parameters - **key** (string) - Required - The key to check. ### Request Example { "key": "mykey" } ### Response #### Success Response (200) - **exists** (integer) - 1 if the key exists, 0 otherwise. #### Response Example { "exists": 1 } ``` -------------------------------- ### Insert Sample Product Data into Upstash Redis Source: https://upstash.com/docs/redis/search/recipes/e-commerce-search Demonstrates how to insert sample product data into Upstash Redis using JSON.set command. This function takes a key, a JSON path, and a JSON object as input. It's useful for populating a Redis database with initial product information. ```typescript await redis.json.set("product:1", "$", { name: "Sony WH-1000XM5 Wireless Headphones", description: "Industry-leading noise cancellation with premium sound quality. 30-hour battery life with quick charging.", brand: "Sony", category: "Electronics > Audio > Headphones", price: 349.99, rating: 4.8, reviewCount: 2847, inStock: true, createdAt: "2024-01-15T00:00:00Z", }); await redis.json.set("product:2", "$", { name: "Apple AirPods Pro 2nd Generation", description: "Active noise cancellation, transparency mode, and spatial audio. MagSafe charging case included.", brand: "Apple", category: "Electronics > Audio > Earbuds", price: 249.99, rating: 4.7, reviewCount: 5621, inStock: true, createdAt: "2024-02-20T00:00:00Z", }); await redis.json.set("product:3", "$", { name: "Bose QuietComfort Ultra Headphones", description: "World-class noise cancellation with immersive spatial audio. Luxurious comfort for all-day wear.", brand: "Bose", category: "Electronics > Audio > Headphones", price: 429.99, rating: 4.6, reviewCount: 1253, inStock: false, createdAt: "2024-03-10T00:00:00Z", }); ``` ```python redis.json().set("product:1", "$", { "name": "Sony WH-1000XM5 Wireless Headphones", "description": "Industry-leading noise cancellation with premium sound quality. 30-hour battery life with quick charging.", "brand": "Sony", "category": "Electronics > Audio > Headphones", "price": 349.99, "rating": 4.8, "reviewCount": 2847, "inStock": True, "createdAt": "2024-01-15T00:00:00Z", }) redis.json().set("product:2", "$", { "name": "Apple AirPods Pro 2nd Generation", "description": "Active noise cancellation, transparency mode, and spatial audio. MagSafe charging case included.", "brand": "Apple", "category": "Electronics > Audio > Earbuds", "price": 249.99, "rating": 4.7, "reviewCount": 5621, "inStock": True, "createdAt": "2024-02-20T00:00:00Z", }) redis.json().set("product:3", "$", { "name": "Bose QuietComfort Ultra Headphones", "description": "World-class noise cancellation with immersive spatial audio. Luxurious comfort for all-day wear.", "brand": "Bose", "category": "Electronics > Audio > Headphones", "price": 429.99, "rating": 4.6, "reviewCount": 1253, "inStock": False, "createdAt": "2024-03-10T00:00:00Z", }) ``` ```redis cli JSON.SET product:1 $ '{"name": "Sony WH-1000XM5 Wireless Headphones", "description": "Industry-leading noise cancellation with premium sound quality. 30-hour battery life with quick charging.", "brand": "Sony", "category": "Electronics > Audio > Headphones", "price": 349.99, "rating": 4.8, "reviewCount": 2847, "inStock": true, "createdAt": "2024-01-15T00:00:00Z"}' JSON.SET product:2 $ '{"name": "Apple AirPods Pro 2nd Generation", "description": "Active noise cancellation, transparency mode, and spatial audio. MagSafe charging case included.", "brand": "Apple", "category": "Electronics > Audio > Earbuds", "price": 249.99, "rating": 4.7, "reviewCount": 5621, "inStock": true, "createdAt": "2024-02-20T00:00:00Z"}' JSON.SET product:3 $ '{"name": "Bose QuietComfort Ultra Headphones", "description": "World-class noise cancellation with immersive spatial audio. Luxurious comfort for all-day wear.", "brand": "Bose", "category": "Electronics > Audio > Headphones", "price": 429.99, "rating": 4.6, "reviewCount": 1253, "inStock": false, "createdAt": "2024-03-10T00:00:00Z"}' ``` -------------------------------- ### LREM Command (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Removes occurrences of a value from a list. ```APIDOC ## LREM ### Description Removes occurrences of a value from a list. ### Method `LREM` ### Endpoint N/A (SDK Usage) ### Parameters #### Request Body - **key** (string) - Required - The list key. - **count** (number) - Required - Number of elements to remove. - **value** (string) - Required - The value to remove. ### Request Example ```ts await redis.lpush("key", "a", "a", "b", "b", "c"); const removed = await redis.lrem("key", 4, "b"); ``` ### Response #### Success Response (200) - **count** (integer) - The number of removed elements. ``` -------------------------------- ### DECR Command Source: https://upstash.com/docs/redis/overall/llms-txt Decrements the integer value of a key by one. ```APIDOC ## DECR Command Example in Python ### Description Decrements the integer value of a key by one. ### Method `redis.decr(key)` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```python redis.set("key", 6) assert redis.decr("key") == 5 ``` ### Response #### Success Response (200) - **value** (integer) - The integer value of the key after being decremented. #### Response Example ```json 5 ``` ``` -------------------------------- ### Success Response (200) for GET operation Source: https://upstash.com/docs/redis/overall/llms-txt Describes the structure of a successful response when retrieving a value using a GET operation, indicating the previous value or None if the key did not exist. ```APIDOC ## Success Response (200) for GET operation ### Description Describes the structure of a successful response when retrieving a value using a GET operation, indicating the previous value or None if the key did not exist. ### Method GET ### Endpoint `/get/` ### Parameters #### Path Parameters - **key** (string) - Required - The key of the value to retrieve. ### Request Example ```bash # Example GET request (details depend on specific API implementation) # curl https://.upstash.io/get/some_key \ # -H "Authorization: Bearer " ``` ### Response #### Success Response (200) - **old_value** (bytes or None) - The previous value of the key, or None if the key did not exist. #### Response Example ```json { "example": "b'initial_value'" } ``` ``` -------------------------------- ### Build Docker Image with Google Cloud Build Source: https://upstash.com/docs/redis/tutorials/cloud_run_sessions This command initiates the build process for a Docker container image on Google Cloud Build, tagging it for later use. Ensure you have authenticated with Google Cloud. ```bash gcloud builds submit --tag gcr.io/cloud-run-sessions/main ``` -------------------------------- ### Install Toast Component for Notifications Source: https://upstash.com/docs/redis/tutorials/notification Installs the 'react-toastify' npm package, which is used to display notification messages to the user in a user-friendly toast format. ```shell npm install --save react-toastify ``` -------------------------------- ### Configure Environment Variables for Supabase Function Source: https://upstash.com/docs/redis/quickstarts/supabase Copies the example environment file to the local configuration directory for the Supabase function. ```shell cp supabase/functions/upstash-redis-counter/.env.example supabase/functions/upstash-redis-counter/.env ``` -------------------------------- ### GET /xread Source: https://upstash.com/docs/redis/sdks/ts/commands/stream/xread Reads data from one or multiple streams starting from specified IDs. ```APIDOC ## GET /xread ### Description Reads data from one or multiple streams, starting from the specified IDs. Use '$' to read only new messages added after the command is issued. ### Method GET ### Endpoint /xread ### Parameters #### Request Body - **key** (string | string[]) - Required - The key(s) of the stream(s). - **id** (string | string[]) - Required - The stream entry ID(s) to start reading from. Must match the number of keys provided. - **options** (object) - Optional - Additional configuration. - **count** (number) - Optional - The maximum number of messages to return per stream. ### Request Example { "key": "mystream", "id": "0-0", "options": { "count": 2 } } ### Response #### Success Response (200) - **data** (Array<[string, Array<[string, string[]]>]> | null) - Returns an array of streams and their messages, or null if no data is available. #### Response Example [ ["mystream", [ ["1638360173533-0", ["field1", "value1", "field2", "value2"]], ["1638360173533-1", ["field1", "value3", "field2", "value4"]] ]] ] ``` -------------------------------- ### POST /functions/load Source: https://upstash.com/docs/redis/overall/llms-txt Loads a Lua library into Redis to register custom functions for server-side execution. ```APIDOC ## POST /functions/load ### Description Loads a Lua library into Redis. The library must start with `#!lua name=` and register functions using `redis.register_function`. ### Method POST ### Endpoint /functions/load ### Parameters #### Request Body - **code** (string) - Required - The Lua source code string. - **replace** (boolean) - Optional - If true, overwrites existing libraries with the same name. ### Request Example { "code": "#!lua name=mylib\nredis.register_function('func', function() return 'ok' end)", "replace": true } ### Response #### Success Response (200) - **libraryName** (string) - The name of the successfully loaded library. #### Response Example { "result": "mylib" } ``` -------------------------------- ### Fastly Redis Instance Creation Source: https://upstash.com/docs/redis/sdks/ts/deployment Initializes a Redis client for Fastly Compute@Edge. Requires configuring a backend in `fastly.toml` and passing the backend name during instantiation. Recommended to create instances manually due to API stability. ```typescript import { Redis } from "@upstash/redis/fastly" const redis = new Redis({ url: , token: , backend: , }) ``` -------------------------------- ### GET /hvals Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves all values associated with a specific hash key in Redis. ```APIDOC ## GET /hvals ### Description Retrieves all values associated with a hash stored at a specified key. Returns an empty list if the key does not exist. ### Method GET ### Endpoint /hvals ### Parameters #### Query Parameters - **key** (string) - Required - The key of the hash. ### Request Example GET /hvals?key=myhash ### Response #### Success Response (200) - **values** (array) - List of values stored in the hash. #### Response Example { "result": ["value1", "value2"] } ``` -------------------------------- ### ZCARD Command (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the number of elements in a sorted set. ```APIDOC ## ZCARD Command ### Description Returns the sorted set cardinality (number of elements) of the sorted set stored at key. ### Method GET ### Endpoint N/A (Redis Command) ### Parameters #### Request Body - **key** (string) - Required - The sorted set key. ### Request Example ```python count = redis.zcard("myset") ``` ### Response #### Success Response (200) - **count** (integer) - The number of elements in the sorted set. ``` -------------------------------- ### PEXPIRE /api/redis/pexpire Source: https://upstash.com/docs/redis/overall/llms-txt Set a key's time to live in milliseconds. ```APIDOC ## PEXPIRE /api/redis/pexpire ### Description Set a key's time to live in milliseconds. ### Method PEXPIRE ### Endpoint /api/redis/pexpire ### Parameters #### Path Parameters - **key** (string) - Required - The key to set expiration for. - **milliseconds** (integer) - Required - The time to live in milliseconds. ### Request Example { "key": "mykey", "milliseconds": 60000 } ### Response #### Success Response (200) - **success** (boolean) - True if the expiration was set successfully. #### Response Example { "success": true } ``` -------------------------------- ### DEL /api/redis/del Source: https://upstash.com/docs/redis/overall/llms-txt Deletes one or multiple keys from the Redis database. ```APIDOC ## DEL /api/redis/del ### Description Delete one or multiple keys. ### Method DEL ### Endpoint /api/redis/del ### Parameters #### Path Parameters - **key** (string) - Required - The key to delete. - **keys** (string[]) - Optional - Multiple keys to delete. ### Request Example { "key": "mykey" } ### Response #### Success Response (200) - **count** (integer) - The number of keys deleted. #### Response Example { "count": 1 } ``` -------------------------------- ### SRANDMEMBER Command Source: https://upstash.com/docs/redis/overall/llms-txt Retrieve one or more random members from a Redis set. ```APIDOC ## SRANDMEMBER ### Description Return one or more random members from a set. ### Method SRANDMEMBER ### Parameters #### Arguments - **key** (str) - Required - The key of the set. - **count** (int) - Optional - The number of members to return. ### Response #### Success Response (200) - **member(s)** (str | List[str]) - A random member if count is not specified, or a list of random members if count is specified. ``` -------------------------------- ### Publish Messages with QStash Client Source: https://upstash.com/docs/redis/howto/vercelintegration Initializes the QStash client using environment variables and publishes a JSON payload to a specified URL. Requires the QSTASH_TOKEN environment variable to be set. ```typescript import { Client } from "@upstash/qstash"; const client = new Client({ token: process.env.QSTASH_TOKEN, }); const res = await client.publishJSON({ url: "https://my-api...", body: { hello: "world", }, }); ``` -------------------------------- ### ZPOPMIN Source: https://upstash.com/docs/redis/overall/llms-txt Removes and returns the element with the lowest score from a sorted set. ```APIDOC ## ZPOPMIN ### Description Removes and returns the element with the lowest score from a sorted set. ### Method `ZPOPMIN` ### Endpoint N/A (SDK Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (SDK Usage) ### Request Example ```typescript const popped = await redis.zpopmin("key", 4); ``` ### Response #### Success Response (200) - elements (Array<[member: string, score: number]>) - An array of elements popped from the sorted set. ``` -------------------------------- ### Upstash Redis LSET Command Example (TypeScript) Source: https://upstash.com/docs/redis/sdks/ts/commands/list/lset Demonstrates how to use the LSET command in Upstash Redis with TypeScript. This involves pushing initial elements to a list and then using LSET to update an element at a specific index. Dependencies include the Upstash Redis client library. ```typescript await redis.lpush("key", "a", "b", "c"); await redis.lset("key", 1, "d"); // list is now ["a", "d", "c"] ``` -------------------------------- ### Redis SET with GET Option (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Sets a key-value pair and returns the old value of the key, if any, before it was updated using the GET option. Useful for atomic updates and retrieving previous states. ```python # Assuming 'redis' is an initialized redis-py client instance # Set an initial value redis.set("mykey", "initial_value") # Use SET with GET option to update and retrieve the old value old_value = redis.set("mykey", "new_value", get=True) print(f"Old value: {old_value}") # Output: b'initial_value' # Verify the new value current_value = redis.get("mykey") print(f"Current value: {current_value}") # Output: b'new_value' # If the key did not exist before, GET option returns None old_value_nonexistent = redis.set("anotherkey", "some_value", get=True) print(f"Old value for nonexistent key: {old_value_nonexistent}") # Output: None ``` -------------------------------- ### Initialize Upstash Redis Client (Python) Source: https://upstash.com/docs/redis/sdks/py/gettingstarted Demonstrates how to initialize both synchronous and asynchronous Upstash Redis clients in Python. Requires UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN credentials. ```python # for sync client from upstash_redis import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") # for async client from upstash_redis.asyncio import Redis redis = Redis(url="UPSTASH_REDIS_REST_URL", token="UPSTASH_REDIS_REST_TOKEN") ``` -------------------------------- ### Initialize and Deploy Supabase Functions Source: https://upstash.com/docs/redis/quickstarts/supabase Commands to create a new Supabase function, run it locally for testing, and deploy it to the Supabase platform. ```bash supabase functions new upstash-redis-counter supabase start supabase functions serve upstash-redis-counter --no-verify-jwt --env-file supabase/functions/upstash-redis-counter/.env supabase functions deploy upstash-redis-counter --no-verify-jwt supabase secrets set --env-file supabase/functions/upstash-redis-counter/.env ``` -------------------------------- ### Deploy and Invoke Serverless Functions Source: https://upstash.com/docs/redis/tutorials/auto_complete_with_serverless_redis Commands to deploy the serverless stack to AWS and invoke the query function using the CLI. Includes both remote cloud invocation and local testing. ```shell serverless deploy ``` ```shell serverless invoke -f query -d '{ "queryStringParameters": {"term":"ca"}}' ``` ```shell serverless invoke local -f query -d '{ "queryStringParameters": {"term":"ca"}}' ``` -------------------------------- ### Configure Upstash MCP SSE Server with Proxy Source: https://upstash.com/docs/redis/overall/llms-txt JSON configuration for setting up the Upstash MCP server in `sse` mode, designed for server deployments. This setup uses a `supergateway` proxy. ```APIDOC ## Configure Upstash MCP SSE Server with Proxy ### Description Configuration for running the Upstash MCP server in SSE mode with a supergateway proxy for local client integration. ### Method N/A (Configuration file) ### Endpoint N/A ### Parameters N/A ### Request Example ```json { "mcpServers": { "upstash": { "command": "npx", "args": [ "-y", "supergateway", "--sse", "https://mcp.upstash.io/sse", "--oauth2Bearer", ":" ] } } } ``` ```json { "servers": { "upstash": { "type": "stdio", "command": "npx", "args": [ "-y", "supergateway", "--sse", "https://mcp.upstash.io/sse", "--oauth2Bearer", ":" ] } } } ``` ``` -------------------------------- ### SUNIONSTORE Command Source: https://upstash.com/docs/redis/overall/llms-txt Stores the members of all sets in the given sets, in a new set. ```APIDOC ## SUNIONSTORE Command API Reference ### Description Stores the members of all sets in the given sets, in a new set. ### Method SUNIONSTORE destinationKey sourceKey [sourceKey ...] ### Endpoint Not applicable (Redis command) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ``` SUNIONSTORE destinationKey key1 key2 ``` ### Response #### Success Response - `type` (set[str]) - The members of the resulting set. ``` -------------------------------- ### Perform Set Difference with SDIFFSTORE in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/commands/set/sdiffstore This example demonstrates how to use the sdiff command to find the difference between two sets. It initializes two sets with members and stores the resulting difference in a destination key. ```typescript 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"] ``` -------------------------------- ### RPOP Command (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Removes and returns the last element(s) from a Redis list. ```APIDOC ## RPOP Command ### Description Removes and returns the last element or elements from a list. ### Method POST ### Endpoint N/A (Redis Command) ### Parameters #### Request Body - **key** (string) - Required - The list key. - **count** (integer) - Optional - Number of elements to pop. ### Request Example ```typescript await redis.rpop("key", 2); ``` ### Response #### Success Response (200) - **elements** (array) - The popped elements. ``` -------------------------------- ### PEXPIREAT /api/redis/pexpireat Source: https://upstash.com/docs/redis/overall/llms-txt Set the expiration for a key as a UNIX timestamp specified in milliseconds. ```APIDOC ## PEXPIREAT /api/redis/pexpireat ### Description Set the expiration for a key as a UNIX timestamp specified in milliseconds. ### Method PEXPIREAT ### Endpoint /api/redis/pexpireat ### Parameters #### Path Parameters - **key** (string) - Required - The key to set expiration for. - **timestamp** (integer) - Required - The expiration timestamp in milliseconds. ### Request Example { "key": "mykey", "timestamp": 1678886400000 } ### Response #### Success Response (200) - **success** (boolean) - True if the expiration was set successfully. #### Response Example { "success": true } ``` -------------------------------- ### HSTRLEN Command Source: https://upstash.com/docs/redis/overall/llms-txt Returns the length of the string value associated with a field in a hash. ```APIDOC ## HSTRLEN ### Description Returns the length of the string value associated with a field in a hash. ### Method GET ### Endpoint /redis/commands/hash/hstrlen ### Parameters #### Request Body - **key** (string) - Required - The hash key. - **field** (string) - Required - The field within the hash. ### Response #### Success Response (200) - **length** (integer) - The length of the string value. ### Response Example { "length": 5 } ``` -------------------------------- ### Run and Deploy SST Application Source: https://upstash.com/docs/redis/quickstarts/ion These commands are used to run the Next.js development server locally and to deploy the application to AWS using SST. The `npm run dev` command starts the local server, while `sst deploy` handles the cloud infrastructure provisioning. ```shell npm run dev sst deploy ``` -------------------------------- ### ZSCAN Command Source: https://upstash.com/docs/redis/overall/llms-txt Iterates through members of a sorted set, handling pagination with a cursor. ```APIDOC ## Iterate All Members of a Sorted Set with ZSCAN (Python) ### Description This Python code snippet shows how to retrieve all elements from a Redis sorted set using the ZSCAN command, handling cursor-based pagination. ### Method GET (or equivalent for command execution) ### Endpoint `/redis/commands/zset/zscan` ### Parameters #### Query Parameters - **key** (string) - Required - The key of the sorted set. - **cursor** (integer) - Required (initially 0) - The cursor for the scan operation. Use the returned cursor for subsequent calls. - **match** (string) - Optional - A pattern to filter the returned elements. ### Request Example ```python import redis r = redis.Redis.from_url("redis://:@:") # Replace with your connection details cursor = 0 results = [] while True: cursor, keys = r.zscan("myzset", cursor, match="*") # Replace "myzset" with your key results.extend(keys) if cursor == 0: break for key, score in results: print(f"Member: {key.decode()}, Score: {score}") ``` ### Response #### Success Response (200) - **elements** (Array<{member: string, score: number}>) - A list of members and their scores. ``` -------------------------------- ### RPUSHX Command Example in Python Source: https://upstash.com/docs/redis/sdks/py/commands/list/rpushx Demonstrates how to use the RPUSHX command in Python to push elements to the end of a list if it exists. It shows successful pushes and the case where the list does not exist. ```python 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 ``` -------------------------------- ### Retrieve keys matching a pattern in Python Source: https://upstash.com/docs/redis/sdks/py/commands/generic/keys Demonstrates how to use the KEYS command in Python to fetch keys based on a specific prefix or to retrieve all keys using a wildcard. Note that this operation can block the database and is not recommended for production environments with large datasets. ```python keys = redis.keys("prefix*") ``` ```python keys = redis.keys("*") ``` -------------------------------- ### HSETNX Command (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Set the value of a hash field only if the field does not exist. ```APIDOC ## HSETNX Command in TypeScript ### Description Set the value of a hash field, only if the field does not exist. ### Method SDK Method ### Endpoint N/A ### Parameters #### Request Body - **key** (string) - Required - The key of the hash. - **field** (string) - Required - The field to set. - **value** (any) - Required - The value to set. ### Request Example ```ts await redis.hsetnx("key", "id", 1) ``` ### Response #### Success Response (200) - **result** (integer) - Returns 1 if the field is new and was set, 0 if the field already existed. #### Response Example ```json 1 ``` ``` -------------------------------- ### Create a language-specific search index Source: https://upstash.com/docs/redis/search/index-management Configures a search index with language-specific tokenization and stemming options. This example demonstrates setting the language to Turkish and disabling stemming for specific fields. ```typescript const addresses = await redis.search.createIndex({ name: "addresses", dataType: "json", prefix: "address:", language: "turkish", schema: s.object({ address: s.string().noStem(), description: s.string(), }), }); ``` ```python addresses = redis.search.create_index( name="addresses", data_type="json", prefix="address:", language="turkish", schema={ "address": {"type": "TEXT", "nostem": True}, "description": "TEXT", }, ) ``` ```bash SEARCH.CREATE addresses ON JSON PREFIX 1 address: LANGUAGE turkish SCHEMA address TEXT NOSTEM description TEXT ``` -------------------------------- ### Configure Redis environment variables Source: https://upstash.com/docs/redis/tutorials/python_url_shortener Sets the necessary environment variables for connecting to the Upstash Redis instance. ```shell export UPSTASH_REDIS_REST_URL= export UPSTASH_REDIS_REST_TOKEN= ``` ```text UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= ``` -------------------------------- ### GET /GETRANGE Source: https://upstash.com/docs/redis/sdks/py/commands/string/getrange Retrieves a substring of the value stored at the specified key based on start and end indices. ```APIDOC ## GETRANGE ### Description Returns a substring of the value stored at the specified key, defined by the start and end offsets. ### Method GET ### Endpoint /GETRANGE ### Parameters #### Query Parameters - **key** (str) - Required - The key of the value to retrieve. - **start** (int) - Required - The start index of the substring (inclusive). - **end** (int) - Required - The end index of the substring (inclusive). ### Request Example ```python redis.set("key", "Hello World") redis.getrange("key", 0, 4) ``` ### Response #### Success Response (200) - **value** (str) - The requested substring. #### Response Example "Hello" ``` -------------------------------- ### Connect and Execute Commands with redis-cli Source: https://upstash.com/docs/redis/overall/llms-txt Establishes a secure TLS connection to an Upstash Redis instance and executes basic key-value operations. ```bash redis-cli --tls -a PASSWORD -h ENDPOINT -p PORT set counter 0 get counter incr counter incr counter ``` -------------------------------- ### GETBIT Command (Python) Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves a single bit at a specific offset from a key in Redis. ```APIDOC ## GETBIT Command ### Description Retrieves the bit value at offset in the string value stored at key. ### Method GET ### Endpoint N/A (Redis Command) ### Parameters #### Request Body - **key** (string) - Required - The key of the string. - **offset** (integer) - Required - The bit offset. ### Request Example ```python bit = redis.getbit(key, 4) ``` ### Response #### Success Response (200) - **value** (integer) - The bit value stored at offset. ``` -------------------------------- ### DELETE /redis/zremrangebylex Source: https://upstash.com/docs/redis/overall/llms-txt Removes elements from a sorted set within a specified lexicographical range. ```APIDOC ## DELETE /redis/zremrangebylex ### Description Removes elements from a sorted set within a specified lexicographical range. ### Method DELETE ### Endpoint /redis/zremrangebylex ### Parameters #### Request Body - **key** (string) - Required - The key of the sorted set. - **minLex** (string) - Required - The minimum lexicographical value. - **maxLex** (string) - Required - The maximum lexicographical value. ### Request Example ```typescript await redis.zremrangebylex("key", "alpha", "omega") ``` ### Response #### Success Response (200) - **count** (integer) - The number of elements removed. #### Response Example ```json { "count": 5 } ``` ``` -------------------------------- ### POST /api/create Source: https://upstash.com/docs/redis/tutorials/roadmapvotingapp Creates a new feature request in the roadmap sorted set. Uses the NX flag to prevent overwriting existing titles. ```APIDOC ## POST /api/create ### Description Adds a new element to the 'roadmap' sorted set in Redis. Validates that the title is present and under 70 characters. ### Method POST ### Endpoint /api/create ### Parameters #### Request Body - **title** (string) - Required - The title of the feature request. ### Request Example { "title": "Add dark mode support" } ### Response #### Success Response (200) - **body** (string) - Returns "success" upon successful creation. #### Response Example { "body": "success" } ``` -------------------------------- ### Install isomorphic-fetch for Node.js < v17 Source: https://upstash.com/docs/redis/sdks/ts/troubleshooting If running on Node.js v17 or earlier without a native fetch polyfill, install the 'isomorphic-fetch' package to resolve 'ReferenceError: fetch is not defined'. This is often provided by platforms like Vercel or Netlify, but bare Node.js installations require manual addition. ```bash npm i isomorphic-fetch ``` -------------------------------- ### XAUTOCLAIM (TypeScript) Source: https://upstash.com/docs/redis/overall/llms-txt Performs a basic XAUTOCLAIM operation to transfer pending messages from a stream. ```APIDOC ## Basic XAUTOCLAIM in TypeScript ### Description Performs a basic XAUTOCLAIM operation to transfer pending messages. It requires the stream key, consumer group name, the new consumer name, the minimum idle time for messages to be claimed, and the starting stream entry ID. The result includes the next start ID for pagination, claimed messages with their data, and any deleted message IDs. ### Method SDK Method Call ### Parameters - **key** (string) - Required - The stream key. - **group** (string) - Required - The consumer group name. - **consumer** (string) - Required - The name of the new consumer. - **min-idle-time** (integer) - Required - The minimum idle time in milliseconds for messages to be claimed. - **start** (string) - Required - The starting stream entry ID. ### Request Example (TypeScript) ```typescript const result = await redis.xautoclaim( "mystream", "mygroup", "consumer1", 60000, "0-0" ); ``` ### Response - **next-id** (string) - The next stream entry ID for pagination. - **messages** (object) - A map of claimed messages, keyed by their IDs, with field-value pairs. - **deleted** (array) - An array of deleted message IDs. ``` -------------------------------- ### Set Up Environment Variables for Upstash Redis Source: https://upstash.com/docs/redis/tutorials/nuxtjs_with_redis Configures environment variables required to connect to your Upstash Redis database. These variables, `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`, are essential for authenticating and connecting to your Redis instance. Alternatively, if using Vercel and Upstash integration, `KV_REST_API_URL` and `KV_REST_API_TOKEN` can be used. ```shell cp .env.example .env UPSTASH_REDIS_REST_URL="" UPSTASH_REDIS_REST_TOKEN="" # Or for Vercel integration: # KV_REST_API_URL= # KV_REST_API_TOKEN= ``` -------------------------------- ### HPEXPIRE Command Source: https://upstash.com/docs/redis/overall/llms-txt Sets a time-to-live (TTL) in milliseconds for a specific field within a hash. ```APIDOC ## HPEXPIRE Command (Python) ### Description Sets a time-to-live (TTL) in milliseconds for a specific field within a hash. ### Method `redis.hpexpire(hash_name: str, field: str, milliseconds: int): List[int]` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters - **hash_name** (str) - Required - The name of the hash. - **field** (str) - Required - The field within the hash. - **milliseconds** (int) - Required - Expiration time in milliseconds. ### Request Example ```python redis.hpexpire(hash_name, field, 1000) ``` ### Response #### Success Response (200) - **List[int]** - A list containing 1 if successful, 0 if the field or hash does not exist. #### Response Example ```json [1] ``` ``` -------------------------------- ### POST /redis/getdel Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves the value of a key and deletes the key in a single atomic operation. ```APIDOC ## POST /redis/getdel ### Description Retrieves the value associated with a key and then deletes the key from Redis. ### Method POST ### Parameters #### Request Body - **key** (string) - Required - The key to get and delete. ### Response #### Success Response (200) - **value** (any) - The value associated with the key before deletion. ``` -------------------------------- ### Create Product Index (TypeScript) Source: https://upstash.com/docs/redis/search/recipes/e-commerce-search Demonstrates how to create a search index for products using the Upstash Redis client in TypeScript. It defines the schema for searchable, filterable, and sortable fields. ```APIDOC ## POST /v1/indexes/products ### Description Creates a search index named 'products' for JSON data with a 'product:' prefix. The schema defines fields like name, description, brand, category, price, rating, reviewCount, inStock, and createdAt with specific search and filtering attributes. ### Method POST ### Endpoint /v1/indexes/products ### Parameters #### Request Body - **name** (string) - Required - The name of the index. - **dataType** (string) - Required - The data type of the index (e.g., 'json'). - **prefix** (string) - Required - The prefix for keys in this index. - **schema** (object) - Required - The schema definition for the index fields. - **name** (object) - Full-text searchable string. - **description** (object) - Full-text searchable string. - **brand** (object) - Text string, no stemming. - **category** (object) - Text string, no tokenization. - **price** (object) - Floating-point number, enables sorting. - **rating** (object) - Floating-point number, enables sorting. - **reviewCount** (object) - Unsigned 64-bit integer. - **inStock** (object) - Boolean. - **createdAt** (object) - Date type, enables fast indexing. ### Request Example ```json { "name": "products", "dataType": "json", "prefix": "product:", "schema": { "name": "TEXT", "description": "TEXT", "brand": {"type": "TEXT", "nostem": true}, "category": {"type": "TEXT", "notokenize": true}, "price": "F64", "rating": "F64", "reviewCount": "U64", "inStock": "BOOL", "createdAt": {"type": "DATE", "fast": true} } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of index creation. #### Response Example ```json { "message": "Index 'products' created successfully." } ``` ``` -------------------------------- ### SUNIONSTORE Command Source: https://upstash.com/docs/redis/overall/llms-txt Represents the SUNIONSTORE command for Redis, used for set union operations. ```APIDOC ## SUNIONSTORE Command ### Description Computes the union of multiple sets and stores the result in a new set. This command is part of Redis's set operations. ### Method POST ### Endpoint /websites/upstash_redis ### Parameters #### Query Parameters - **destination** (str) - Required - The key where the resulting set will be stored. #### Request Body - **keys** (array) - Required - An array of keys representing the sets to perform the union on. ### Request Example ```redis SUNIONSTORE destination_key key1 key2 key3 ``` ### Response #### Success Response (200) - **count** (integer) - The number of elements in the resulting set. #### Response Example ```json { "count": 5 } ``` ``` -------------------------------- ### Create Product Index (Python) Source: https://upstash.com/docs/redis/search/recipes/e-commerce-search Shows how to create a search index for products using the Upstash Redis client in Python. It outlines the schema definition for various field types. ```APIDOC ## POST /v1/indexes/products ### Description Creates a search index named 'products' for JSON data with a 'product:' prefix using Python. The schema defines fields for text search, filtering, and sorting, similar to the TypeScript example. ### Method POST ### Endpoint /v1/indexes/products ### Parameters #### Request Body - **name** (string) - Required - The name of the index. - **data_type** (string) - Required - The data type of the index (e.g., 'json'). - **prefix** (string) - Required - The prefix for keys in this index. - **schema** (dict) - Required - The schema definition for the index fields. - **name** (string) - Full-text searchable string. - **description** (string) - Full-text searchable string. - **brand** (dict) - Text string, no stemming. - **category** (dict) - Text string, no tokenization. - **price** (string) - Floating-point number, enables sorting. - **rating** (string) - Floating-point number, enables sorting. - **reviewCount** (string) - Unsigned 64-bit integer. - **inStock** (string) - Boolean. - **createdAt** (dict) - Date type, enables fast indexing. ### Request Example ```python { "name": "products", "data_type": "json", "prefix": "product:", "schema": { "name": "TEXT", "description": "TEXT", "brand": {"type": "TEXT", "nostem": True}, "category": {"type": "TEXT", "notokenize": True}, "price": "F64", "rating": "F64", "reviewCount": "U64", "inStock": "BOOL", "createdAt": {"type": "DATE", "fast": True} } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of index creation. #### Response Example ```json { "message": "Index 'products' created successfully." } ``` ``` -------------------------------- ### Get Hash Field Count with Python Source: https://upstash.com/docs/redis/overall/llms-txt Illustrates how to get the number of fields in a hash stored in Upstash Redis using Python. It includes setting hash fields with `HSET` and then retrieving the count using `HLEN`. ```python # Assuming 'redis' is an initialized Upstash Redis client instance # Check initial count (should be 0 if hash does not exist or is empty) assert redis.hlen("myhash") == 0 # Set fields in the hash redis.hset("myhash", mapping={ "field1": "Hello", "field2": "World" }) # Get the count of fields in the hash assert redis.hlen("myhash") == 2 ``` -------------------------------- ### Retrieve Hash Fields with Expiration Options in TypeScript Source: https://upstash.com/docs/redis/sdks/ts/commands/hash/hgetex Examples demonstrating how to use the HGETEX command with various expiration strategies including seconds, milliseconds, Unix timestamps, and persistence. These snippets show how to handle existing data and manage TTL settings for Redis hashes. ```ts await redis.hset("user:123", { name: "John", email: "john@example.com" }); const result = await redis.hgetex("user:123", { ex: 60 }, "name", "email"); console.log(result); ``` ```ts await redis.hset("session:abc", { token: "xyz123", user: "john" }); const result = await redis.hgetex("session:abc", { px: 30000 }, "token", "user"); console.log(result); ``` ```ts await redis.hset("cache:data", { value: "cached" }); const futureTime = Math.floor(Date.now() / 1000) + 3600; const result = await redis.hgetex("cache:data", { exat: futureTime }, "value"); console.log(result); ``` ```ts await redis.hset("temp:data", { info: "temporary" }); const futureTime = Date.now() + 60000; const result = await redis.hgetex("temp:data", { pxat: futureTime }, "info"); console.log(result); ``` ```ts await redis.hset("user:456", { name: "Jane" }); await redis.expire("user:456", 300); const result = await redis.hgetex("user:456", { persist: true }, "name"); console.log(result); ``` ```ts await redis.hset("data:xyz", { field1: "value1", field2: "value2" }); const result = await redis.hgetex("data:xyz", {}, "field1", "field2"); console.log(result); ``` ```ts await redis.hset("user:789", { name: "Bob" }); const result = await redis.hgetex("user:789", {}, "name", "email"); console.log(result); ``` -------------------------------- ### Fuzzy Search in Upstash Redis (Redis CLI) Source: https://upstash.com/docs/redis/search/query-operators/field-operators/fuzzy Provides examples of executing fuzzy search commands directly via the Redis CLI for Upstash Redis. This includes basic fuzzy matching, specifying custom edit distances, enabling transposition handling, and performing multi-word searches with fuzzy logic. These commands utilize the RediSearch module. ```bash # Simple fuzzy (distance 1, handles single typos) SEARCH.QUERY products '{"name": {"$fuzzy": "headphon"}}' # Custom distance for more tolerance SEARCH.QUERY products '{"name": {"$fuzzy": {"value": "haedphone", "distance": 2, "transpositionCostOne": false}}}' # Handle character transpositions efficiently SEARCH.QUERY products '{"name": {"$fuzzy": {"value": "haedphone", "distance": 1, "transpositionCostOne": true}}}' # Combine prefix with transposition for robust autocomplete SEARCH.QUERY products '{"name": {"$fuzzy": {"value": "haedpho", "prefix": true, "transpositionCostOne": true}}}' # Multiple words - matches documents containing both terms (with fuzzy tolerance) SEARCH.QUERY products '{"name": {"$fuzzy": "wireles headphons"}}' ``` -------------------------------- ### POST /zset/zinterstore Source: https://upstash.com/docs/redis/overall/llms-txt Calculates the intersection of multiple sorted sets and stores the result in a destination key. ```APIDOC ## POST /zset/zinterstore ### Description Calculates the intersection of sets and stores the result in a key. ### Method POST ### Endpoint /zset/zinterstore ### Parameters #### Request Body - **destination** (str) - Required - The key to store the result in. - **keys** (List[str]) - Required - The keys of the sets to compare. - **weights** (List[float]) - Optional - The weights to apply to the sets. - **aggregate** (enum) - Optional - The aggregation function ("SUM" | "MIN" | "MAX"). - **withscores** (bool) - Optional - Whether to include scores in the result. ### Request Example ```json { "command": "ZINTERSTORE", "destination": "dest_set", "keys": ["key1", "key2"], "weights": [1.0, 0.5], "aggregate": "SUM", "withscores": false } ``` ### Response #### Success Response (200) - **integer** - The number of elements in the resulting set. #### Response Example ```json 2 ``` ``` -------------------------------- ### Install Upstash Redis with PyPI Source: https://upstash.com/docs/redis/sdks/py/gettingstarted Installs the upstash-redis Python package using pip. This is the first step to using the library in your Python projects. ```bash pip install upstash-redis ``` -------------------------------- ### LPOS Command Source: https://upstash.com/docs/redis/overall/llms-txt Finds the index of an element in a Redis list. Supports options for rank and count. ```APIDOC ## LPOS Command ### Description Finds the index of an element in a Redis list. Supports options for rank and count. ### Method GET (or equivalent for command execution) ### Endpoint `/redis/commands/list/lpos` ### Parameters #### Path Parameters None #### Query Parameters - **key** (string) - Required - The key of the list. - **element** (string) - Required - The element to find. - **options** (object) - Optional - Options for rank and count. - **rank** (number) - Optional - The rank of the element to find (e.g., 1 for first, -1 for last). - **count** (number) - Optional - The maximum number of occurrences to return. ### Request Example (Basic) ```typescript await redis.lpos("key", "b"); ``` ### Request Example (With Rank) ```typescript await redis.lpos("key", "b", { rank: 2 }); ``` ### Request Example (With Count) ```typescript await redis.lpos("key", "b", { count: 2 }); ``` ### Response #### Success Response (200) - **result** (number or Array) - The index (or indices) of the element in the list. ``` -------------------------------- ### Query Stream Entries in Reverse Order with XREVRANGE Source: https://upstash.com/docs/redis/sdks/py/commands/stream/xrevrange Demonstrates how to use the XREVRANGE command in Python to fetch stream entries. Examples include fetching all entries, limiting the result count, and querying a specific ID range. ```python result = redis.xrevrange("mystream", "+", "-") ``` ```python result = redis.xrevrange("mystream", "+", "-", count=2) ``` ```python result = redis.xrevrange("mystream", end="1638360173533-2", start="1638360173533-0") ``` -------------------------------- ### POST /xgroup-setid Source: https://upstash.com/docs/redis/overall/llms-txt Sets the last delivered ID for a consumer group within a Redis stream. ```APIDOC ## POST /xgroup-setid ### Description Set the last delivered ID for a consumer group. This command allows you to specify which message ID a consumer group should start processing from. ### Method POST ### Endpoint /websites/upstash-redis ### Parameters #### Request Body - **key** (str) - Required - The key of the stream. - **group** (str) - Required - The consumer group name. - **id** (str) - Required - The stream entry ID to set as the last delivered ID. - **entries_read** (int) - Optional - Set the number of entries read by the group. ### Request Example { "key": "mystream", "group": "mygroup", "id": "0-0" } ### Response #### Success Response (200) - **result** (bool) - Returns "OK" if the ID was set successfully. #### Response Example { "result": "OK" } ``` -------------------------------- ### LTRIM Redis Command Source: https://upstash.com/docs/redis/overall/llms-txt Documentation for the LTRIM command used to trim a list to a specified range. ```APIDOC ## LTRIM ### Description Trim a list to the specified range. ### Method LTRIM ### Endpoint N/A ### Parameters #### Request Body - **key** (str) - Required - The key of the list. - **start** (int) - Required - The index of the first element to keep. - **stop** (int) - Required - The index of the last element to keep. ### Response #### Success Response (200) - **result** (bool) - Returns `True` if the list was trimmed, `False` otherwise. ``` -------------------------------- ### MSET Command JSON Request Source: https://upstash.com/docs/redis/overall/llms-txt Demonstrates the JSON structure for executing an MSET command to set multiple keys and values in Redis. ```json { "command": "MSET", "args": [ { "key1": 1, "key2": "hello", "key3": {"a": 1, "b": "hello"} } ] } ``` -------------------------------- ### HPEXPIREAT Command Source: https://upstash.com/docs/redis/overall/llms-txt Sets an expiration time in milliseconds for a specific field within a Redis hash. ```APIDOC ## HPEXPIREAT Command ### Description Sets an expiration time in milliseconds for a specific field within a Redis hash. ### Method `redis.hpexpireat(hash_name, field, timestamp_in_milliseconds)` ### Endpoint N/A (Client-side command) ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```python redis.hset(hash_name, field, value) assert redis.hpexpireat(hash_name, field, int(time.time() * 1000) + 1000) == [1] ``` ### Response #### Success Response (200) - **List**: A list containing a single element, 1, if the timeout was set. An empty list if the field or the key does not exist. #### Response Example ```json [1] ``` ``` -------------------------------- ### POST /redis/zadd Source: https://upstash.com/docs/redis/overall/llms-txt Adds one or more members to a sorted set, or updates its score if it already exists. ```APIDOC ## POST /redis/zadd ### Description Adds all the specified members with the specified scores to the sorted set stored at key. ### Method POST ### Parameters #### Request Body - **key** (string) - Required - The key of the sorted set. - **mapping** (object) - Required - Dictionary of member-score pairs. - **nx** (boolean) - Optional - Only set elements that don't exist. - **xx** (boolean) - Optional - Only update elements that already exist. - **gt** (boolean) - Optional - Only update if new score is greater than current. ### Response #### Success Response (200) - **count** (integer) - The number of elements added to the sorted sets. ``` -------------------------------- ### Create a search index safely with EXISTOK Source: https://upstash.com/docs/redis/search/index-management Creates a search index only if it does not already exist. This prevents errors when attempting to recreate an existing index. ```typescript const cache = await redis.search.createIndex({ name: "cache", dataType: "string", prefix: "cache:", existsOk: true, schema: s.object({ content: s.string(), }), }); ``` ```python cache = redis.search.create_index( name="cache", data_type="string", prefixes="cache:", exists_ok=True, schema={ "content": "TEXT", }, ) ``` ```bash SEARCH.CREATE cache ON STRING PREFIX 1 cache: EXISTSOK SCHEMA content TEXT ``` -------------------------------- ### Paginate Results with Limit and Offset in Redis CLI Source: https://upstash.com/docs/redis/search/querying Demonstrates pagination using the Redis CLI with `LIMIT` and `OFFSET` clauses. `LIMIT` sets the number of results to return, and `OFFSET` skips a specified number of initial results, enabling the fetching of specific data pages. ```bash # Page 1: first 10 results (with optional offset) SEARCH.QUERY products '{"description": "wireless"}' LIMIT 10 # Page 2: results 11-20 SEARCH.QUERY products '{"description": "wireless"}' LIMIT 10 OFFSET 10 # Page 3: results 21-30 SEARCH.QUERY products '{"description": "wireless"}' LIMIT 10 OFFSET 20 ``` -------------------------------- ### TOUCH /api/redis/touch Source: https://upstash.com/docs/redis/overall/llms-txt Alters the last access time of a key(s). Returns the number of existing keys specified. ```APIDOC ## TOUCH /api/redis/touch ### Description Alters the last access time of a key(s). Returns the number of existing keys specified. ### Method TOUCH ### Endpoint /api/redis/touch ### Parameters #### Path Parameters - **keys** (string[]) - Required - The keys to update the access time for. ### Request Example ```json { "keys": ["key1", "key2"] } ``` ### Response #### Success Response (200) - **count** (integer) - The number of existing keys specified. #### Response Example ```json { "count": 2 } ``` ``` -------------------------------- ### Rename Key Source: https://upstash.com/docs/redis/overall/llms-txt Renames an existing key to a new name. Overwrites the destination key if it already exists. ```json { "oldKey": "mykey", "newKey": "newkey" } ``` -------------------------------- ### POST /redis/hset Source: https://upstash.com/docs/redis/overall/llms-txt Set multiple fields and values in a Redis hash using a dictionary of key-value pairs. ```APIDOC ## POST /redis/hset ### Description Set multiple fields and values in a Redis hash. ### Method POST ### Endpoint /redis/hset ### Parameters #### Request Body - **key** (string) - Required - The key of the hash. - **values** (object) - Required - A dictionary of field-value pairs to set. ### Request Example { "key": "myhash", "values": { "field1": "Hello", "field2": "World" } } ### Response #### Success Response (200) - **result** (integer) - The number of fields that were added to the hash. #### Response Example { "result": 2 } ``` -------------------------------- ### Configure Flask and Socket.IO with Redis Source: https://upstash.com/docs/redis/overall/llms-txt Initializes a Flask application and configures Socket.IO to use Redis as a message broker, including environment variable setup for secure TLS connections. ```python from flask import Flask, render_template from flask_socketio import SocketIO import os app = Flask(__name__) app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'a_default_secret_key') redis_url = os.environ.get('REDIS_URL') ``` -------------------------------- ### RPOP Command API Reference Source: https://upstash.com/docs/redis/overall/llms-txt Retrieves and removes the last element from a list using the RPOP command. ```APIDOC ## RPOP Command API Reference ### Description Retrieves and removes the last element from a list. ### Method GET ### Endpoint /redis/commands/list/rpop ### Parameters #### Query Parameters - **key** (string) - Required - The key of the list. - **count** (integer) - Optional - How many elements to pop. If not specified, a single element is popped. ### Response #### Success Response (200) - **response** (TValue | TValue[] | null) - The popped element(s). If `count` was specified, an array of elements is returned, otherwise a single element is returned. If the list is empty, `null` is returned. #### Response Example { "element": "value" } ``` -------------------------------- ### Node.js/Browser Redis Instance Creation Source: https://upstash.com/docs/redis/sdks/ts/deployment Instantiates a Redis client for Node.js and browser environments. It supports loading credentials from environment variables or direct configuration. Ensure `fetch` is available or use the `with-fetch` import for older Node.js versions. ```typescript import { Redis } from "@upstash/redis" const redis = new Redis({ url: , token: , }) // or load directly from env const redis = Redis.fromEnv() ``` ```typescript import { Redis } from "@upstash/redis/with-fetch"; ```