Class RedisStore

A Redis-based key-value store for LangGraph state.

This store persists data in Redis, providing durable storage for graph state. It can be used as a standalone key-value store or with LangGraph's checkpointing.

Example

// Basic key-value storage
const store = new RedisStore();
await store.put(["users", "123"], "prefs", { theme: "dark" });
const item = await store.get(["users", "123"], "prefs");

Example

// Vector search with embeddings
import { OpenAIEmbeddings } from "@langchain/openai";
const store = new RedisStore({
index: {
dims: 1536,
embeddings: new OpenAIEmbeddings({ modelName: "text-embedding-3-small" }),
}
});

// Store documents
await store.put(["docs"], "doc1", { text: "Python tutorial" });
await store.put(["docs"], "doc2", { text: "TypeScript guide" });

// Search by similarity
const results = await store.search(["docs"], { query: "python programming" });

Example

// Custom Redis configuration
const store = new RedisStore({
url: "redis://username:[email protected]:6379",
ttl: 86400, // 1 day TTL
keyPrefix: "myapp:store:"
});

Example

// Using with IORedis client
import IORedis from "ioredis";

const redisClient = new IORedis("redis://localhost:6379");
const store = new RedisStore({
client: redisClient,
ttl: 3600 // 1 hour TTL
});

Example

// Advanced filtering with MongoDB-style operators
const store = new RedisStore();

// Add some items
await store.put(["products"], "p1", { name: "Widget", price: 10, inStock: true });
await store.put(["products"], "p2", { name: "Gadget", price: 20, inStock: true });
await store.put(["products"], "p3", { name: "Tool", price: 15, inStock: false });

// Search with filters
const expensiveProducts = await store.search(["products"], {
filter: { price: { $gt: 12 } }
});

const inStockProducts = await store.search(["products"], {
filter: { inStock: true }
});

const specificProducts = await store.search(["products"], {
filter: { name: { $in: ["Widget", "Tool"] } }
});

Example

// Batching operations for efficiency
const store = new RedisStore();

const results = await store.batch([
// Get operation
{ namespace: ["users"], key: "user1" },
// Put operation
{ namespace: ["users"], key: "user2", value: { name: "Alice" } },
// Search operation
{ namespacePrefix: ["products"], filter: { category: "electronics" }, limit: 5 }
]);

// results[0] = Get result
// results[1] = null (put operations return null)
// results[2] = Search results

Example

// Using the legacy key-value API
const store = new RedisStore();

// Set a value
await store.set("session:user123", { authenticated: true });

// Get a value
const session = await store.getLegacy("session:user123");

// Check if key exists
const exists = await store.has("session:user123");

// Set TTL for a key
await store.setTTL("session:user123", 1800); // 30 minutes

// Get remaining TTL
const remainingTtl = await store.getTTL("session:user123");

// List all keys
const allKeys = await store.keys();

// Clear all data
await store.clear();

Example

// Properly starting and stopping the store
import { createGraph } from "@langchain/langgraph";

const store = new RedisStore();

// Register for proper lifecycle management with a graph
const builder = createGraph();
builder.addPersistenceOptions({
stateStore: store
});

// Or manually control the lifecycle
store.start(); // Connect to Redis

try {
// Use the store...
} finally {
store.stop(); // Disconnect when done
}

Hierarchy

  • BaseStore
    • RedisStore

Constructors

Properties

_redisConfig?: IndexConfig & {
    __tokenizedFields?: [string, string[]][];
}

Type declaration

  • Optional __tokenizedFields?: [string, string[]][]
client: RedisAdapter
clientOwned: boolean = false
connectionPromise: null | Promise<unknown> = null
data: Map<string, Map<string, Item>> = ...
isConnecting: boolean = false
keyPrefix: string
ttl?: number
vectors: Map<string, Map<string, Map<string, number[]>>> = ...

Accessors

Methods

  • Execute multiple operations in a single batch. Implementation of BaseStore abstract method.

    Type Parameters

    • Op extends readonly Operation[]

    Parameters

    • operations: Op

      Array of operations to execute

    Returns Promise<OperationResults<Op>>

    Promise resolving to results matching the operations

  • Creates a standardized item from Redis data.

    Parameters

    • namespace: string[]
    • key: string
    • value: Record<string, any>
    • Optional metadata: Record<string, any>

    Returns Item

  • Delete an item from storage. Implementation of the BaseStore abstract method.

    Parameters

    • namespace: string[]
    • key: string

    Returns Promise<void>

  • Check if a namespace matches a pattern

    Parameters

    • namespace: string[]
    • pattern: string[]
    • matchType: "prefix" | "suffix"

    Returns boolean

  • Extract texts for embedding from put operations Used internally by batch method

    Parameters

    • ops: PutOperation[]

    Returns [string[], [string[], string, string][]]

  • Filter items based on a filter condition

    Parameters

    • items: Item[]

      Items to filter

    • Optional filter: Record<string, any>

      Filter condition

    Returns Item[]

    Filtered items

  • Get an item by namespace and key. Implementation of the BaseStore abstract method.

    Parameters

    • namespace: string[]
    • key: string

    Returns Promise<null | Item>

  • Insert vector embeddings

    Parameters

    • texts: string[]

      The texts to embed

    • items: [string[], string, string][]

      The items containing the texts

    • Optional embeddings: number[][]

      Optional pre-computed embeddings

    Returns Promise<void>

    Promise that resolves when vectors are inserted

  • List and filter namespaces in the store. Used to explore data organization and navigate the namespace hierarchy.

    Parameters

    • Optional options: {
          limit?: number;
          maxDepth?: number;
          offset?: number;
          prefix?: string[];
          suffix?: string[];
      }

      Options for listing namespaces

      • Optional limit?: number
      • Optional maxDepth?: number
      • Optional offset?: number
      • Optional prefix?: string[]
      • Optional suffix?: string[]

    Returns Promise<string[][]>

    Promise resolving to list of namespace paths

    Example

    // List all namespaces under "documents"
    await store.listNamespaces({
    prefix: ["documents"],
    maxDepth: 2
    });

    // List namespaces ending with "v1"
    await store.listNamespaces({
    suffix: ["v1"],
    limit: 50
    });
  • List namespaces with filtering based on match conditions.

    Parameters

    • op: ListNamespacesOperation

    Returns Promise<string[][]>

  • Paginate results

    Parameters

    • items: SearchItem[]

      Items to paginate

    • offset: number = 0

      Offset to start from

    • limit: number = 10

      Maximum number of items to return

    Returns SearchItem[]

    Paginated items

  • Put an item into storage. Implementation of the BaseStore abstract method.

    Parameters

    • namespace: string[]
    • key: string
    • value: Record<string, any>
    • Optional index: string[]

    Returns Promise<void>

  • Score results based on similarity to a query embedding

    Parameters

    • items: Item[]

      Items to score

    • queryEmbedding: number[]

      The query embedding to compare against

    Returns Promise<SearchItem[]>

    Scored items

  • Search for items. Implementation of the BaseStore abstract method.

    Parameters

    • namespacePrefix: string[]
    • options: {
          filter?: Record<string, any>;
          limit?: number;
          offset?: number;
          query?: string;
      } = {}
      • Optional filter?: Record<string, any>
      • Optional limit?: number
      • Optional offset?: number
      • Optional query?: string

    Returns Promise<SearchItem[]>

  • Stores vector embeddings in Redis

    Parameters

    • texts: Record<string, [string[], string, string][]>
    • embeddings: number[][]

    Returns Promise<void>