Skip to main content

Sorted set collections

A sorted set in Momento Cache is a collection of unique elements with a value (String, Byte[], etc.) and score (signed double 64-bit float) pair. The elements in a sorted set are ordered by score.

info

Momento collection types use a CollectionTTL to specify their TTL behavior. This is an optional argument for all "write" operations.

Sorted set methods

SortedSetPutElement

Adds a new or updates an existing sorted set element in a sorted set.

  • If the set does not exist, this method creates a new sorted set collection with the element passed in.

  • If the set exists, the element is added to the sorted set if that value doesn't exist. If the value of that element does exist, that element is overwritten.

NameTypeDescription
cacheNameStringName of the cache.
setNameStringName of the sorted set collection to be altered.
valueString | Byte[]The value of the element to be added to the sorted set by this operation.
scorenumberThe score of the element to be added to the sorted set by this operation.
ttlCollectionTTL objectTTL for the sorted set collection. This TTL takes precedence over the TTL used when initializing a cache connection client.
Method response object
  • Success
  • Error

See response objects for specific information.

const result = await cacheClient.sortedSetPutElement(cacheName, 'test-sorted-set', 'test-value', 5);
switch (result.type) {
case CacheSortedSetPutElementResponse.Success:
console.log("Value 'test-value' with score '5' added successfully to sorted set 'test-sorted-set'");
break;
case CacheSortedSetPutElementResponse.Error:
throw new Error(
`An error occurred while attempting to call cacheSortedSetPutElement on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
info
Full example code and imports can be found here

SortedSetPutElements

Adds new or updates existing sorted set elements in a sorted set collection.

  • If the set does not exist, this method creates a new sorted set collection with the element(s) passed in.

  • If the set exists, for each SortedSetElement in the array, each element is added to the sorted set if that value doesn't exist. If the value of that element does exist, that element is overwritten.

NameTypeDescription
cacheNameStringName of the cache.
setNameStringName of the sorted set collection to be altered.
elementsSortedSetElement[]Elements to be added to the sorted set by this operation.
ttlCollectionTTL objectTTL for the sorted set collection. This TTL takes precedence over the TTL used when initializing a cache connection client.
Method response object
  • Success
  • Error

See response objects for specific information.

const result = await cacheClient.sortedSetPutElements(
cacheName,
'test-sorted-set',
new Map<string, number>([
['key1', 10],
['key2', 20],
])
);
switch (result.type) {
case CacheSortedSetPutElementsResponse.Success:
console.log("Elements added successfully to sorted set 'test-sorted-set'");
break;
case CacheSortedSetPutElementsResponse.Error:
throw new Error(
`An error occurred while attempting to call cacheSortedSetPutElements on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
info
Full example code and imports can be found here

SortedSetFetchByRank

Fetch elements of sorted set, optionally filtered by rank, and return them in ascending or descending order.

NameTypeDescription
cacheNameStringName of the cache.
setNameStringName of the sorted set collection.
startRankOptional[integer]The inclusive start rank of the results. Default is zero.
endRankOptional[integer]The exclusive end rank of the results. Default is null, ie up to and including the element ranked last.
orderAscending | DescendingThe order you want the sorted set returned.
Method response object
  • Hit
    • elements(): SortedSetElement[]
  • Miss
  • Error

See response objects for specific information.

await cacheClient.sortedSetPutElements(
cacheName,
'test-sorted-set',
new Map<string, number>([
['key1', 10],
['key2', 20],
])
);
const result = await cacheClient.sortedSetFetchByRank(cacheName, 'test-sorted-set');

// simplified style; assume the value was found
console.log(`Sorted set fetched: ${result.value()!}`);

// pattern-matching style; safer for production code
switch (result.type) {
case CacheSortedSetFetchResponse.Hit:
console.log("Values from sorted set 'test-sorted-set' fetched by rank successfully- ");
result.value().forEach(res => {
console.log(`${res.value} : ${res.score}`);
});
break;
case CacheSortedSetFetchResponse.Miss:
console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`);
break;
case CacheSortedSetFetchResponse.Error:
throw new Error(
`An error occurred while attempting to call cacheSortedSetFetchByRank on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
info
Full example code and imports can be found here

SortedSetFetchByScore

Fetch elements of sorted set, optionally filtered by score, and return them in ascending or descending order.

NameTypeDescription
cacheNameStringName of the cache.
setNameStringName of the sorted set collection.
minScoreOptional[double]The inclusive low score of the results. Default is -inf, ie include through the lowest score.
maxScoreOptional[double]The inclusive high score of the results. Default is +inf, ie include through the highest score.
orderAscending | DescendingThe order you want the sorted set returned.
offsetOptional[int]The offset, inclusive, into the filtered list from which to start returning results. Default is 0, ie do not filter. If specified, must be non-negative.
countOptional[int]The maximum number of results from the filtered list to return. Default is null, ie no limit. If specified, must be strictly positive.
Method response object
  • Hit
    • elements(): SortedSetElement[]
  • Miss
  • Error

See response objects for specific information.

await cacheClient.sortedSetPutElements(
cacheName,
'test-sorted-set',
new Map<string, number>([
['key1', 100],
['key2', 25],
])
);
const result = await cacheClient.sortedSetFetchByScore(cacheName, 'test-sorted-set');

// simplified style; assume the value was found
console.log(`Fetched values from sorted set: ${result.value()!}`);

// pattern-matching style; safer for production code
switch (result.type) {
case CacheSortedSetFetchResponse.Hit:
console.log("Values from sorted set 'test-sorted-set' fetched by score successfully- ");
result.value().forEach(res => {
console.log(`${res.value} : ${res.score}`);
});
break;
case CacheSortedSetFetchResponse.Miss:
console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`);
break;
case CacheSortedSetFetchResponse.Error:
throw new Error(
`An error occurred while attempting to call cacheSortedSetFetchByScore on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
info
Full example code and imports can be found here

SortedSetGetScore

Gets an element's score from the sorted set, indexed by value.

NameTypeDescription
cacheNameStringName of the cache.
setNameStringName of the sorted set collection.
valueString | BytesThe value to get the score of.
Method response object
  • Cache hit
    • Score: number
  • Cache miss (if the sorted set does not exist)
  • Error

See response objects for specific information.

await cacheClient.sortedSetPutElements(
cacheName,
'test-sorted-set',
new Map<string, number>([
['key1', 10],
['key2', 20],
])
);
const result = await cacheClient.sortedSetGetScore(cacheName, 'test-sorted-set', 'key1');

// simplified style; assume the value was found
console.log(`Element with value 'key1' has score: ${result.score()!}`);

// pattern-matching style; safer for production code
switch (result.type) {
case CacheSortedSetGetScoreResponse.Hit:
console.log(`Element with value 'key1' has score: ${result.score()}`);
break;
case CacheSortedSetGetScoreResponse.Miss:
console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`);
break;
case CacheSortedSetGetScoreResponse.Error:
throw new Error(
`An error occurred while attempting to call cacheSortedSetFetchGetScore on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
info
Full example code and imports can be found here

SortedSetGetScores

Gets the scores associated with a list of elements from the sorted set, indexed by value.

NameTypeDescription
cacheNameStringName of the cache.
setNameStringName of the sorted set collection.
valuesString[] | Bytes[]An array of values to get the score of.
Method response object
  • Cache hit
    • Elements() (returns hit/miss per element)
      • Hit:
        • Score: number
      • Miss
  • Cache miss (if the sorted set does not exist)
  • Error

See response objects for specific information.

await cacheClient.sortedSetPutElements(
cacheName,
'test-sorted-set',
new Map<string, number>([
['key1', 10],
['key2', 20],
])
);
const result = await cacheClient.sortedSetGetScores(cacheName, 'test-sorted-set', ['key1', 'key2']);

// simplified style; assume the value was found
console.log(`Retrieved scores from sorted set: ${result.value()!}`);

// pattern-matching style; safer for production code
switch (result.type) {
case CacheSortedSetGetScoresResponse.Hit:
console.log('Element scores retrieved successfully -');
result.valueMap().forEach((value, key) => {
console.log(`${key} : ${value}`);
});
break;
case CacheSortedSetGetScoresResponse.Miss:
console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`);
break;
case CacheSortedSetGetScoresResponse.Error:
throw new Error(
`An error occurred while attempting to call cacheSortedSetFetchGetScores on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
info
Full example code and imports can be found here

SortedSetRemoveElement

Removes an element from a sorted set, indexed by value.

NameTypeDescription
cacheNameStringName of the cache.
setNameStringName of the set collection to be altered.
valueString | BytesValue of the element to be removed by this operation.
Method response object
  • Success
  • Error

See response objects for specific information.

await cacheClient.sortedSetPutElement(cacheName, 'test-sorted-set', 'test-value', 10);
const result = await cacheClient.sortedSetRemoveElement(cacheName, 'test-sorted-set', 'test-value');
switch (result.type) {
case CacheSortedSetRemoveElementResponse.Success:
console.log("Element with value 'test-value' removed successfully");
break;
case CacheSortedSetRemoveElementResponse.Error:
throw new Error(
`An error occurred while attempting to call cacheSortedSetRemoveElement on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
info
Full example code and imports can be found here

SortedSetRemoveElements

Removes elements from a sorted set, indexed by values.

NameTypeDescription
cacheNameStringName of the cache.
setNameStringName of the set collection to be altered.
valuesString[] | Bytes[]Values of the elements to be removed by this operation.

You can remove either one or a specific group of elements.

Method response object
  • Success
  • Error

See response objects for specific information.

await cacheClient.sortedSetPutElements(
cacheName,
'test-sorted-set',
new Map<string, number>([
['key1', 10],
['key2', 20],
])
);
const result = await cacheClient.sortedSetRemoveElements(cacheName, 'test-sorted-set', ['key1', 'key2']);
switch (result.type) {
case CacheSortedSetRemoveElementsResponse.Success:
console.log("Elements with value 'key1' and 'key2 removed successfully");
break;
case CacheSortedSetRemoveElementsResponse.Error:
throw new Error(
`An error occurred while attempting to call cacheSortedSetRemoveElements on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
info
Full example code and imports can be found here

SortedSetGetRank

What position is the element, in the specified sorted set?

NameTypeDescription
cacheNameStringName of the cache.
setNameStringName of the sorted set collection to be altered.
valueString | BytesValue of the element to retrieve the score of.
orderOptional[Ascending | Descending]The order in which sorted set will be sorted to determine the rank.
Method response object
  • Hit
    • Rank: integer
  • Miss
  • Error

See response objects for specific information.

await cacheClient.sortedSetPutElements(
cacheName,
'test-sorted-set',
new Map<string, number>([
['key1', 10],
['key2', 20],
['key3', 30],
])
);
const result = await cacheClient.sortedSetGetRank(cacheName, 'test-sorted-set', 'key2');

// simplified style; assume the value was found
console.log(`Element with value 'key1' has rank: ${result.rank()!}`);

// pattern-matching style; safer for production code
switch (result.type) {
case CacheSortedSetGetRankResponse.Hit:
console.log(`Element with value 'key1' has rank: ${result.rank()}`);
break;
case CacheSortedSetGetRankResponse.Miss:
console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`);
break;
case CacheSortedSetGetRankResponse.Error:
throw new Error(
`An error occurred while attempting to call cacheSortedSetFetchGetRank on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
info
Full example code and imports can be found here

SortedSetIncrementScore

Adds to the score of an element. If the value is missing from the sorted set, this method sets the value to the amount to increment by.

note

The resulting incremented score must be between -9223372036854775808 and 9223372036854775807, ie. a signed double 64-bit float. If not, there will be an error response.

Examples:

  • When the element does not exist in the sorted set, SortedSetIncrementScore(cacheName, setName, value, 10) will set the element's score to 10.
  • When the existing element is a value:score of "{ 'KesselRun' : 12 }" , SortedSetIncrementScore(cacheName, setName, value, 10) will set the element's score to 22.
NameTypeDescription
cacheNameStringName of the cache.
setNameStringName of the sorted set collection to be altered.
valueString | BytesValue for the element to be incremented by this operation.
amountNumberThe quantity to add to the score. May be positive, negative, or zero. Defaults to 1.
ttlCollectionTTL objectTTL for the sorted set collection. This TTL takes precedence over the TTL used when initializing a cache connection client.
Method response object
  • Success
    • Value: number - the new value after incrementing
  • Error

See response objects for specific information.

await cacheClient.sortedSetPutElement(cacheName, 'test-sorted-set', 'test-value', 10);
const result = await cacheClient.sortedSetIncrementScore(cacheName, 'test-sorted-set', 'test-value', 1);
switch (result.type) {
case CacheSortedSetIncrementScoreResponse.Success:
console.log(`Score for value 'test-value' incremented successfully. New score - ${result.score()}`);
break;
case CacheSortedSetIncrementScoreResponse.Error:
throw new Error(
`An error occurred while attempting to call cacheSortedSetIncrementScore on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
info
Full example code and imports can be found here

SortedSetElement

A value and score makes up each element in a sorted set.

Example: { "TomHocusXaster" : 1138 }

NameTypeDescription
ValueString | BytesValue for the sorted set element.
ScoreSigned double 64-bit floatScore the element.

A SortedSetElement can exist by itself or as part of an array of SortedSetElements.

SortedSetLength

Get the number of entries in a sorted set collection.

NameTypeDescription
cacheNameStringName of the cache.
sortedSetNameStringName of the sorted set collection to be checked.
Method response object
  • Hit
    • length(): Number
  • Miss
  • Error

See response objects for specific information.

  let _length: u32 = cache_client
.sorted_set_length(cache_name, "sorted_set_name")
.await?
.try_into()
.expect("Expected a list length!");
info
Full example code and imports can be found here

SortedSetLengthByScore

For an existing sorted set collection, it finds all of the values between the specified min and max score and returns the length.

NameTypeDescription
cacheNameStringName of the cache.
sortedSetNameStringName of the sorted set collection to be checked.
minScoreOptional[double]The inclusive low score of the results. Default is -inf, ie include through the lowest score.
maxScoreOptional[double]The inclusive high score of the results. Default is +inf, ie include through the highest score.
Method response object
  • Hit
    • length(): Number
  • Miss
  • Error

See response objects for specific information.