getThreadsByResourceIdPaginated リファレンス
getThreadsByResourceIdPaginated
関数は、特定のリソースIDに関連付けられたスレッドをページネーション機能付きで取得します。この機能は、大量のスレッドを扱う際のパフォーマンスとメモリ使用量の問題に対処し、ナビゲーション用のメタデータと共に管理しやすい単位で結果を返します。
使用例
import { Memory } from "@mastra/core/memory";
const memory = new Memory(config);
// デフォルトパラメータでの基本的な使用
const result = await memory.getThreadsByResourceIdPaginated({
resourceId: "resource-123",
page: 0,
perPage: 100,
});
console.log(result.threads);
console.log(result.total);
console.log(result.hasMore);
// ソート機能付きのカスタムページネーション
const customResult = await memory.getThreadsByResourceIdPaginated({
resourceId: "resource-123",
page: 2,
perPage: 50,
orderBy: "updatedAt",
sortDirection: "ASC",
});
// ページネーション結果の処理
let currentPage = 0;
let hasMorePages = true;
while (hasMorePages) {
const pageResult = await memory.getThreadsByResourceIdPaginated({
resourceId: "user-456",
page: currentPage,
perPage: 25,
orderBy: "createdAt",
sortDirection: "DESC",
});
// スレッドを処理
pageResult.threads.forEach(thread => {
console.log(`Thread: ${thread.id}, Created: ${thread.createdAt}`);
});
hasMorePages = pageResult.hasMore;
currentPage++;
}
パラメータ
resourceId:
string
スレッドを取得するリソースのID。
page:
number
取得するページ番号。正の整数を指定してください。
perPage:
number
1ページあたりに返すスレッド数。正の整数を指定してください。
orderBy?:
ThreadOrderBy
スレッドの並び順に使用するフィールド。'createdAt'または'updatedAt'を指定可能。デフォルト: 'createdAt'
sortDirection?:
ThreadSortDirection
並び順の方向。'ASC'または'DESC'を指定可能。デフォルト: 'DESC'
型定義
type ThreadOrderBy = 'createdAt' | 'updatedAt';
type ThreadSortDirection = 'ASC' | 'DESC';
interface ThreadSortOptions {
orderBy?: ThreadOrderBy;
sortDirection?: ThreadSortDirection;
}
interface PaginationInfo {
total: number; // 全ページのスレッド総数
page: number; // 現在のページ番号
perPage: number; // ページあたりのスレッド数
hasMore: boolean; // 追加ページの有無
}
戻り値
threads:
StorageThreadType[]
指定された条件でソートされた現在のページのスレッド配列。
total:
number
リソースIDに関連付けられたスレッドの総数(全ページ)。
page:
number
現在のページ番号。
perPage:
number
リクエストで指定されたページあたりのスレッド数。
hasMore:
boolean
追加の結果ページが存在するかどうかを示す。
技術的な注意事項
パフォーマンスに関する考慮事項
このメソッドは、LIMIT/OFFSET操作(または同等の操作)を使用してデータベースレベルでのページネーションを実行します。これにより、すべてのスレッドを取得してアプリケーションコードでページネーションを行う場合と比較して、パフォーマンスとメモリ使用量が向上します。
デフォルト値
orderBy
: デフォルトは"createdAt"
sortDirection
: デフォルトは"DESC"
(新しいものから順)
getThreadsByResourceIdとの関係
ページネーション版(getThreadsByResourceIdPaginated
)は、既存のgetThreadsByResourceId
メソッドを補完します:
- リソースのすべてのスレッドが必要な場合は
getThreadsByResourceId
を使用 - 大量のスレッドコレクションを扱う場合やUIページネーションを実装する場合は
getThreadsByResourceIdPaginated
を使用
両方のメソッドは一貫性のために同じソートオプションをサポートしています。
エラーハンドリング
try {
const result = await memory.getThreadsByResourceIdPaginated({
resourceId: "resource-123",
page: 0,
perPage: 100,
});
if (result.threads.length === 0) {
console.log("このリソースのスレッドが見つかりませんでした");
}
} catch (error) {
console.error("ページネーションされたスレッドの取得に失敗しました:", error);
}
関連項目
- Memory Class Reference
- getThreadsByResourceId - ページネーションなし版
- Getting Started with Memory (スレッド/リソースの概念をカバー)
- createThread
- getThreadById