Leaderboards API reference
Momento Leaderboardsを使用する
Momento Leaderboardsは、専用のAPIを備えたトップクラスのサービスであり、数千万のアイテムを持つリーダーボードと、迅速なingestion/querying/updatesをサポートします。
Leaderboard Client
リーダーボードを作成し、操作するには、まずLeaderboardClientを作成する必要があります。
- JavaScript
new PreviewLeaderboardClient({
configuration: LeaderboardConfigurations.Laptop.v1(),
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
そして、キャッシュとリーダーボード名を指定して、リーダーボードを作成することができます。
- JavaScript
// You can create multiple leaderboards using the same leaderboard client
// but with different cache and leaderboard names
leaderboardClient.leaderboard('test-cache', 'momento-leaderboard');
leaderboardClient.leaderboard('test-cache', 'acorns-leaderboard');
// Leaderboard and cache names must be non-empty strings
try {
leaderboardClient.leaderboard('test-cache', ' ');
} catch (error) {
console.log('Expected error creating a leaderboard with invalid leaderboard name:', error);
}
Leaderboard メソッド
要素をUpsert
リーダボードにまだ要素が存在しない場合、要素を挿入します。要素がすでにリーダーボードに存在する場合は、要素を更新する。upsertコールは成功するか失敗するかのどちらかです。
IDは、プレーヤー識別子、セッション識別子、ブラウザ識別子、またはこのスコアボードに使用したい他の種類の識別子にすることができます。0から2^63-1まで、64ビットの符号なし整数で指定できます。idはリーダーボードに一度しか表示されません。つまり、プレイヤーが2つのidを持っていない限り、一人のプレイヤーに対して2つのスコアを表示することはできません。
名前 | タイプ | 説明 |
---|---|---|
elements | Map<number, number> | upsertする要素(id,scoreのペア)のマップまたはレコード |
Method response object
- Success
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
// 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 'test-cache': ${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 'test-cache': ${result2.errorCode()}: ${result2.message()}`
);
}
アップサートはバッチ操作として実装されているので、大規模なリーダーボードでは、最大8192要素のバッチでアップサートを行うことができます。
- JavaScript
// To upsert a large number of elements, you must upsert
// in batches of up to 8192 elements at a time.
const elements = [...Array(20000).keys()].map(i => {
return {id: i + 1, score: i * Math.random()};
});
for (let i = 0; i < 20000; 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})`);
}
}
スコアで要素を取得する
指定された最小スコアと最大スコアの範囲内にある要素を取得します。
同じスコアを持つ要素は、IDに基づいた英数字順で返されます (例えば、同じスコアを持つ要素のIDは、[1, 2, 10, 123, 2, 234, ...]
ではなく [1, 10, 123, 234, ...]
の順に返されます)。
名前 | タイプ | 説明 |
---|---|---|
minScore | Optional[number] | スコア範囲の下限を含む。デフォルトは -inf |
maxScore | Optional[number] | スコア範囲の排他的上限値。デフォルトは +inf |
order | Optional[Ascending / Descending] | 要素を取得する順番。デフォルトは昇順で、0が最も低いスコアとなります。 |
offset | Optional[number] | 最初の要素を返す前にスキップする要素の数。注意: これは最初に返す要素のスコアではなく、最初の要素を返す前にスキップする結果セットの要素数です。 |
count | Optional[number] | 返す要素の最大数。デフォルトは 8192 で、これはリクエストごとに取得できる最大数です。 |
Method response object
- Success
- values(): {
id
: number,score
: number,rank
: number}[]
- values(): {
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
// 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 'test-cache': ${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 'test-cache': ${result2.errorCode()}: ${result2.message()}`
);
}
FetchByScore はバッチ処理として実装されているので、大規模なリーダーボードの場合、最大 8192 要素までまとめて取得することができます。offset` パラメータを使用すると、要求されたスコア範囲に含まれる複数の要素を、要求された要素の終わりを示す空のリストが返されるまでページ送りすることができます。
- JavaScript
// Use the offset option to paginate through your results if your leaderboard
// has more than 8192 elements.
for (let offset = 0; offset < 20000; 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 [${offset}, ${offset + 8192})`);
}
}
ランク別に要素を取得する
指定された最小ランクと最大ランクの範囲内にある要素を取得する。
名前 | タイプ | 説明 |
---|---|---|
startRank | number | ランク範囲の包含下限。デフォルトは0。 |
endRank | number | ランク範囲の排他的上限。デフォルトは startRank + 8192 です。 |
order | Optional[Ascending / Descending] | 要素を取得する順番。デフォルトは昇順で、0が最も低いスコアとなります。 |
Method response object
- Success
- values(): {
id
: number,score
: number,rank
: number}[]
- values(): {
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
// 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 'test-cache': ${result1.errorCode()}: ${result1.message()}`
);
}
大規模なリーダーボードでは、最大8192個の要素を一括でフェッチする必要があります。
- JavaScript
// Use the startRank and endRank options to paginate through your leaderboard
// if your leaderboard has more than 8192 elements
for (let rank = 0; rank < 20000; 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 [${rank}, ${rank + 8192})`);
}
}
IDで要素を取得する
要素IDのリストを指定して要素を取得する。
名前 | タイプ | 説明 |
---|---|---|
ids | Array<number > | 順位を取得する要素のID |
order | Optional[Ascending / Descending] | 要素を取得する順番。デフォルトは昇順で、0が最も低いスコアとなります。 |
Method response object
- Success
- values(): {
id
: number,score
: number,rank
: number}[]
- values(): {
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
// 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 'test-cache': ${result.errorCode()}: ${result.message()}`
);
}
リーダーボードの長さを取得する
リーダーボードのエントリー数を取得する。リーダーボードの名前は Leaderboard
オブジェクトから推測されます。
Method response object
- Success
- length(): number
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
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 'test-cache': ${result.errorCode()}: ${result.message()}`
);
}
要素を削除する
指定されたIDを持つ要素を削除します。
名前 | タイプ | 説明 |
---|---|---|
ids | Array<number > | 削除したい要素のID配列。 |
Method response object
- Success
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
// 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 'test-cache': ${result.errorCode()}: ${result.message()}`
);
}
大規模なリーダーボードでは、最大8192個の要素を一括して削除する必要があります。
- JavaScript
// You can remove batches of 8192 elements at a time
const ids = [...Array(20000).keys()];
for (let i = 0; i < 20000; 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})`);
}
}
リーダーボードの削除
リーダーボードを削除する。リーダーボードの名前は Leaderboard
オブジェクトから推測されます。
Method response object
- Success
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
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 'test-cache': ${result.errorCode()}: ${result.message()}`
);
}