メインコンテンツまでスキップ

Momentoリーダーボードの使用

Momento Leaderboardsは、専用のAPIを備えたトップクラスのサービスであり、数千万のアイテムを持つリーダーボードと、迅速な取り込み/照会/更新をサポートします。

リーダーボード・クライアントの方法


リーダーボードクライアントの作成

リーダーボードを作成し、操作するには、まずLeaderboardClientを作成する必要があります。

パラメータ


configuration - LeaderboardConfiguration

  • リーダーボードクライアントを設定するためのオプションです。詳細については、SDK Configuration Objects を参照してください。

credentialProvider - CredentialProvider


オプション・パラメータ


戻り値


新しいリーダーボードを作成し、既存のリーダーボードと相互作用することができる PreviewLeaderboardClient オブジェクト。

new PreviewLeaderboardClient({
configuration: LeaderboardConfigurations.Laptop.v1(),
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});

リーダーボードの作成

LeaderboardClient を使用して、キャッシュとリーダーボード名を指定してリーダーボードを作成します。

パラメータ


cacheName - string

  • どのキャッシュにリーダーボードを作成するか

leaderboardName - string

  • リーダーボードの名前をどうするか

オプション・パラメータ


戻り値


リーダーボードオブジェクトまたはエラー

// You can create multiple leaderboards using the same leaderboard client
// but with different cache and leaderboard names
leaderboardClient.leaderboard(cacheName, 'momento-leaderboard');
leaderboardClient.leaderboard(cacheName, 'acorns-leaderboard');

// Leaderboard and cache names must be non-empty strings
try {
leaderboardClient.leaderboard(cacheName, ' ');
} catch (error) {
console.log('Expected error creating a leaderboard with invalid leaderboard name:', error);
}

リーダーボードの方法


要素のアップサート

リーダボードにまだ要素が存在しない場合、要素を挿入します。要素がすでにリーダーボードに存在する場合は、要素を更新します。。upsert呼び出しは成功するか失敗するかのどちらかです。

アップサートはバッチ操作として実装されているので、大規模なリーダーボードでは、最大8192要素のバッチでアップサートを行うことができます。
// To upsert a large number of elements, you must upsert
// in batches of up to 8192 elements at a time.
// This example shows how to paginate for a large value of `totalNumElements`, such as `20000`.
const elements = [...Array(totalNumElements).keys()].map(i => {
return {id: i + 1, score: i * Math.random()};
});
for (let i = 0; i < totalNumElements; i += 8192) {
// Create a Map containing 8192 elements at a time
const batch = new Map(elements.slice(i, i + 8192).map(obj => [obj['id'], obj['score']]));

// Then upsert one batch at a time until all elements have been ingested
const result = await leaderboard.upsert(batch);
if (result instanceof LeaderboardUpsert.Error) {
console.log(`Error upserting batch [${i}, ${i + 8192})`);
}
}

パラメータ


elements - Dictionary

  • Dictionary of (id, score) pairs to upsert.

    • id: integer
    • score: double
  • idはプレイヤー識別子、セッション識別子、ブラウザ識別子、またはこのスコアボードに使いたい他の種類の識別子にすることができます。0から2^63-1まで、64ビットの符号なし整数で指定できます。

  • つまり、1人の選手が2つのIDを持っていない限り、2つのスコアを持つことはできません!


オプション・パラメータ


戻り値


以下のいずれか:

// Upsert a set of elements as a Map
const elements1: Map<number, number> = new Map([
[123, 100.0],
[234, 200.0],
[345, 300.0],
[456, 400.0],
]);
const result1 = await leaderboard.upsert(elements1);
if (result1 instanceof LeaderboardUpsert.Success) {
console.log('Successfully upserted elements to leaderboard');
} else if (result1 instanceof LeaderboardUpsert.Error) {
console.log('Upsert error:', result1.message());
throw new Error(
`An error occurred while attempting to call upsert on leaderboard 'momento-leaderboard' in cache '${cacheName}': ${result1.errorCode()}: ${result1.message()}`
);
}

// Or upsert a set of elements as a Record
const elements2: Record<number, number> = {
567: 500,
678: 600,
789: 700,
890: 800,
};
const result2 = await leaderboard.upsert(elements2);
if (result2 instanceof LeaderboardUpsert.Success) {
console.log('Successfully upserted elements to leaderboard');
} else if (result2 instanceof LeaderboardUpsert.Error) {
console.log('Upsert error:', result2.message());
throw new Error(
`An error occurred while attempting to call upsert on leaderboard 'momento-leaderboard' in cache '${cacheName}': ${result2.errorCode()}: ${result2.message()}`
);
}

スコアで要素を取得

指定された最小スコアと最大スコアの範囲内にある要素を取得します。

同じスコアを持つ要素は、そのIDに基づいた英数字の順番で返されます(例えば、同じスコアを持つ要素のIDは、[1, 2, 10, 123, 2, 234, ...] ではなく [1, 10, 123, 234, ...] の順番で返されます)。

FetchByScoreはバッチ操作として実装されているので、大規模なリーダーボードでは、最大8192個の要素をバッチでフェッチすることができます。

offsetパラメータを使用すると、要求されたスコア範囲内にある複数の要素を、要求された要素の終わりを示す空のリストを受け取るまで、ページ送りすることができます。

// Use the offset option to paginate through your results if your leaderboard
// has more than 8192 elements.
// This example shows how to paginate for a large value of `totalNumElements`, such as `20000`.
for (let offset = 0; offset < totalNumElements; offset += 8192) {
const result = await leaderboard.fetchByScore({offset});
if (result instanceof LeaderboardFetch.Success) {
processBatch(result.values());
} else if (result instanceof LeaderboardFetch.Error) {
console.log(
`Error fetching batch by score [${offset}, ${offset + 8192}) (${result.errorCode()}: ${result.message()})`
);
}
}

パラメータ


オプション・パラメータ


minScore - double

  • スコア範囲の下限を含む。デフォルトは -inf です。

maxScore - double

  • スコア範囲の排他的上限値。デフォルトは +inf です。

order - LeaderboardOrder enum

  • Enum values: Ascending, Descending

  • 要素を取得する順番。デフォルトは昇順で、0が最も低いスコアとなります。


offset - integer

  • 最初の要素を返す前にスキップする要素数。デフォルトは0。

  • Note: これは最初に返す要素のスコアではなく、最初の要素を返す前にスキップする結果セットの要素数です。


count - integer

  • 返す要素の最大数。デフォルトは 8192 で、これはリクエストごとに取得できる最大数です。

戻り値


以下のいずれか:

// By default, FetchByScore will fetch the elements from the entire score range
// with zero offset in ascending order. It can return 8192 elements at a time.
const result1 = await leaderboard.fetchByScore();
if (result1 instanceof LeaderboardFetch.Success) {
console.log('Successfully fetched elements using open score range:');
result1.values().forEach(element => {
console.log(`\tId: ${element.id} | Rank: ${element.rank} | Score: ${element.score}`);
});
} else if (result1 instanceof LeaderboardFetch.Error) {
throw new Error(
`An error occurred while attempting to call fetchByScore with no options on leaderboard 'momento-leaderboard' in cache '${cacheName}': ${result1.errorCode()}: ${result1.message()}`
);
}

// Example specifying all FetchByScore options. You can provide any subset of these options
// to modify your FetchByScore request.
const result2 = await leaderboard.fetchByScore({
minScore: 10,
maxScore: 600,
order: LeaderboardOrder.Descending,
offset: 2,
count: 10,
});
if (result2 instanceof LeaderboardFetch.Success) {
console.log('Successfully fetched elements by score using all options:');
result2.values().forEach(element => {
console.log(`\tId: ${element.id} | Rank: ${element.rank} | Score: ${element.score}`);
});
} else if (result2 instanceof LeaderboardFetch.Error) {
throw new Error(
`An error occurred while attempting to call fetchByScore with all options on leaderboard 'momento-leaderboard' in cache '${cacheName}': ${result2.errorCode()}: ${result2.message()}`
);
}

ランク別に要素を取り出す

指定された最小ランクと最大ランクの範囲内にある要素を取得する。

大規模なリーダーボードでは、最大8192個の要素を一括でフェッチすることができます。
// Use the startRank and endRank options to paginate through your leaderboard
// if your leaderboard has more than 8192 elements
// This example shows how to paginate for a large value of `totalNumElements`, such as `20000`.
for (let rank = 0; rank < totalNumElements; rank += 8192) {
const result = await leaderboard.fetchByRank(rank, rank + 8192, {order: LeaderboardOrder.Descending});
if (result instanceof LeaderboardFetch.Success) {
processBatch(result.values());
} else if (result instanceof LeaderboardFetch.Error) {
console.log(
`Error fetching batch by rank [${rank}, ${rank + 8192}) (${result.errorCode()}: ${result.message()})`
);
}
}

パラメータ


startRank - integer

  • ランク範囲の包含下限。デフォルトは0。

endRank - integer

  • ランク範囲の排他的な上限。デフォルトは startRank + 8192 です。

オプション・パラメータ


order - LeaderboardOrder enum

  • Enum values: Ascending, Descending

  • 要素を取得する順番。デフォルトは昇順で、0が最も低いスコアとなります。


戻り値


以下のいずれか:

// By default, FetchByRank will fetch the elements in the range [startRank, endRank)
// in ascending order, meaning rank 0 is for the lowest score.
const result1 = await leaderboard.fetchByRank(0, 10);
if (result1 instanceof LeaderboardFetch.Success) {
console.log('Successfully fetched elements in rank range [0,10)');
result1.values().forEach(element => {
console.log(`\tId: ${element.id} | Rank: ${element.rank} | Score: ${element.score}`);
});
} else if (result1 instanceof LeaderboardFetch.Error) {
throw new Error(
`An error occurred while attempting to call fetchByRank with no options on leaderboard 'momento-leaderboard' in cache '${cacheName}': ${result1.errorCode()}: ${result1.message()}`
);
}

IDで要素を取り出す

要素IDのリストが与えられた要素を取得します。

パラメータ


ids - List

  • フェッチする要素のIDを表す整数のリスト。

オプション・パラメータ


order - LeaderboardOrder enum

  • Enum values: Ascending, Descending

  • 要素を取得する順番。デフォルトは昇順で、0が最も低いスコアとなります。


戻り値


以下のいずれか:

// Provide a list of element IDs to get their ranks in ascending or descending order
const result = await leaderboard.getRank([123, 456, 789], {
order: LeaderboardOrder.Descending,
});
if (result instanceof LeaderboardFetch.Success) {
console.log('Successfully fetched the rank of 3 elements:');
result.values().forEach(element => {
console.log(`\tId: ${element.id} | Rank: ${element.rank} | Score: ${element.score}`);
});
} else if (result instanceof LeaderboardFetch.Error) {
throw new Error(
`An error occurred while attempting to call getRank on leaderboard 'momento-leaderboard' in cache '${cacheName}': ${result.errorCode()}: ${result.message()}`
);
}

リーダーボードの長さを取得

リーダーボードのエントリー数を取得する。リーダーボードの名前は Leaderboard オブジェクトから推測される。

パラメータ


オプション・パラメータ


戻り値


以下のいずれか:

const result = await leaderboard.length();
if (result instanceof LeaderboardLength.Success) {
console.log('Successfully retrieved leaderboard length:', result.length());
} else if (result instanceof LeaderboardLength.Error) {
throw new Error(
`An error occurred while attempting to call length on leaderboard 'momento-leaderboard' in cache '${cacheName}': ${result.errorCode()}: ${result.message()}`
);
}

要素を取り除く

指定されたIDを持つ要素を削除します。

大規模なリーダーボードでは、最大8192個の要素を一括して削除できます。
// You can remove batches of 8192 elements at a time.
// This example shows how to paginate for a large value of `totalNumElements`, such as `20000`.
const ids = [...Array(totalNumElements).keys()];
for (let i = 0; i < totalNumElements; i += 8192) {
const result = await leaderboard.removeElements(ids.slice(i, i + 8192));
if (result instanceof LeaderboardRemoveElements.Error) {
console.log(`Error removing batch [${i}, ${i + 8192}) (${result.errorCode()}: ${result.message()})`);
}
}

パラメータ


ids - List

  • 削除したい要素のIDのリスト

オプション・パラメータ


オプションパラメータ


以下のいずれか:

// Provide a list of element IDs to delete those elements
const result = await leaderboard.removeElements([123, 456, 789]);
if (result instanceof LeaderboardRemoveElements.Success) {
console.log('Successfully removed elements');
} else if (result instanceof LeaderboardRemoveElements.Error) {
throw new Error(
`An error occurred while attempting to call removeElements on leaderboard 'momento-leaderboard' in cache '${cacheName}': ${result.errorCode()}: ${result.message()}`
);
}

リーダーボードの削除

リーダーボードを削除する。リーダーボードの名前は Leaderboard オブジェクトから取得可能です。

パラメータ


オプションパラメータ


戻り値


以下のいずれか:

const result = await leaderboard.delete();
if (result instanceof LeaderboardDelete.Success) {
console.log('Successfully deleted the leaderboard');
} else if (result instanceof LeaderboardDelete.Error) {
throw new Error(
`An error occurred while attempting to call delete on leaderboard 'momento-leaderboard' in cache '${cacheName}': ${result.errorCode()}: ${result.message()}`
);
}