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);
if (result instanceof CacheSortedSetPutElement.Success) {
console.log("Value 'test-value' with score '5' added successfully to sorted set 'test-sorted-set'");
} else if (result instanceof CacheSortedSetPutElement.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()}`
);
}

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],
])
);
if (result instanceof CacheSortedSetPutElements.Success) {
console.log("Elements added successfully to sorted set 'test-sorted-set'");
} else if (result instanceof CacheSortedSetPutElements.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()}`
);
}

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');
if (result instanceof CacheSortedSetFetch.Hit) {
console.log("Values from sorted set 'test-sorted-set' fetched by rank successfully- ");
result.valueArray().forEach(res => {
console.log(`${res.value} : ${res.score}`);
});
} else if (result instanceof CacheSortedSetFetch.Miss) {
console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`);
} else if (result instanceof CacheSortedSetFetch.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()}`
);
}

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');
if (result instanceof CacheSortedSetFetch.Hit) {
console.log("Values from sorted set 'test-sorted-set' fetched by score successfully- ");
result.valueArray().forEach(res => {
console.log(`${res.value} : ${res.score}`);
});
} else if (result instanceof CacheSortedSetFetch.Miss) {
console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`);
} else if (result instanceof CacheSortedSetFetch.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()}`
);
}

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');
if (result instanceof CacheSortedSetGetScore.Hit) {
console.log(`Element with value 'key1' has score: ${result.score()}`);
} else if (result instanceof CacheSortedSetGetScore.Miss) {
console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`);
} else if (result instanceof CacheSortedSetGetScore.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()}`
);
}

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']);
if (result instanceof CacheSortedSetGetScores.Hit) {
console.log('Element scores retrieved successfully -');
result.valueMap().forEach((value, key) => {
console.log(`${key} : ${value}`);
});
} else if (result instanceof CacheSortedSetGetScores.Miss) {
console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`);
} else if (result instanceof CacheSortedSetGetScores.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()}`
);
}

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');
if (result instanceof CacheSortedSetRemoveElement.Success) {
console.log("Element with value 'test-value' removed successfully");
} else if (result instanceof CacheSortedSetRemoveElement.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()}`
);
}

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']);
if (result instanceof CacheSortedSetRemoveElements.Success) {
console.log("Elements with value 'key1' and 'key2 removed successfully");
} else if (result instanceof CacheSortedSetRemoveElements.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()}`
);
}

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.
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');
if (result instanceof CacheSortedSetGetRank.Hit) {
console.log(`Element with value 'key1' has rank: ${result.rank()}`);
} else if (result instanceof CacheSortedSetGetRank.Miss) {
console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`);
} else if (result instanceof CacheSortedSetGetRank.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()}`
);
}

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);
if (result instanceof CacheSortedSetIncrementScore.Success) {
console.log(`Score for value 'test-value' incremented successfully. New score - ${result.score()}`);
} else if (result instanceof CacheSortedSetIncrementScore.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()}`
);
}

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.

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.