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.
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.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
setName | String | Name of the sorted set collection to be altered. |
value | String | Byte[] | The value of the element to be added to the sorted set by this operation. |
score | number | The score of the element to be added to the sorted set by this operation. |
ttl | CollectionTTL object | TTL 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.
- JavaScript
- Rust
- Elixir
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()}`
);
}
cache_client
.sorted_set_put_element(cache_name, "sorted_set_name", "value", 1.0)
.await?;
println!("Element added to sorted set");
case Momento.CacheClient.sorted_set_put_element(
client,
"test-cache",
"test-sorted-set",
"test-value",
5.0
) do
{:ok, _} ->
IO.puts(
"Value 'test-value' with score '5' added successfully to sorted set 'test-sorted-set'"
)
{:error, error} ->
IO.puts(
"An error occurred while attempting to put an element into sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}"
)
raise error
end
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.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
setName | String | Name of the sorted set collection to be altered. |
elements | SortedSetElement[] | Elements to be added to the sorted set by this operation. |
ttl | CollectionTTL object | TTL 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.
- JavaScript
- Rust
- Elixir
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()}`
);
}
cache_client
.sorted_set_put_elements(
cache_name,
"sorted_set_name",
vec![("value1", 1.0), ("value2", 2.0)],
)
.await?;
println!("Elements added to sorted set");
case Momento.CacheClient.sorted_set_put_elements(client, "test-cache", "test-sorted-set", [
{"key1", 10.0},
{"key2", 20.0}
]) do
{:ok, _} ->
IO.puts("Elements added successfully to sorted set 'test-sorted-set'")
{:error, error} ->
IO.puts(
"An error occurred while attempting to put elements into sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}"
)
raise error
end
SortedSetFetchByRank
Fetch elements of sorted set, optionally filtered by rank, and return them in ascending or descending order.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
setName | String | Name of the sorted set collection. |
startRank | Optional[integer] | The inclusive start rank of the results. Default is zero. |
endRank | Optional[integer] | The exclusive end rank of the results. Default is null , ie up to and including the element ranked last. |
order | Ascending | Descending | The order you want the sorted set returned. |
Method response object
- Hit
- elements(): SortedSetElement[]
- Miss
- Error
See response objects for specific information.
- JavaScript
- Rust
- Elixir
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()}`
);
}
let response = cache_client
.sorted_set_fetch_by_rank(
cache_name,
"sorted_set_name",
SortedSetOrder::Ascending,
None,
None,
)
.await?;
match response {
SortedSetFetchResponse::Hit { value } => match value.into_strings() {
Ok(vec) => {
println!("Fetched elements: {:?}", vec);
}
Err(error) => {
eprintln!("Error converting values into strings: {}", error);
}
},
SortedSetFetchResponse::Miss => println!("Cache miss"),
}
{:ok, _} =
Momento.CacheClient.sorted_set_put_elements(client, "test-cache", "test-sorted-set", [
{"key1", 10.0},
{"key2", 20.0}
])
case Momento.CacheClient.sorted_set_fetch_by_rank(client, "test-cache", "test-sorted-set") do
{:ok, hit} ->
IO.puts("Values from sorted set 'test-sorted-set' fetched by rank successfully:")
IO.inspect(hit.value)
:miss ->
IO.puts("Sorted Set 'test-sorted-set' was not found in cache 'test-cache'")
{:error, error} ->
IO.puts(
"An error occurred while attempting to fetch by rank on sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}"
)
raise error
end
SortedSetFetchByScore
Fetch elements of sorted set, optionally filtered by score, and return them in ascending or descending order.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
setName | String | Name of the sorted set collection. |
minScore | Optional[double] | The inclusive low score of the results. Default is -inf , ie include through the lowest score. |
maxScore | Optional[double] | The inclusive high score of the results. Default is +inf , ie include through the highest score. |
order | Ascending | Descending | The order you want the sorted set returned. |
offset | Optional[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. |
count | Optional[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.
- JavaScript
- Rust
- Elixir
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()}`
);
}
let response = cache_client
.sorted_set_fetch_by_score(cache_name, "sorted_set_name", SortedSetOrder::Ascending)
.await?;
match response {
SortedSetFetchResponse::Hit { value } => match value.into_strings() {
Ok(vec) => {
println!("Fetched elements: {:?}", vec);
}
Err(error) => {
eprintln!("Error converting values into strings: {}", error);
}
},
SortedSetFetchResponse::Miss => println!("Cache miss"),
}
{:ok, _} =
Momento.CacheClient.sorted_set_put_elements(client, "test-cache", "test-sorted-set", [
{"key1", 10.0},
{"key2", 20.0}
])
case Momento.CacheClient.sorted_set_fetch_by_score(client, "test-cache", "test-sorted-set") do
{:ok, hit} ->
IO.puts("Values from sorted set 'test-sorted-set' fetched by score successfully:")
IO.inspect(hit.value)
:miss ->
IO.puts("Sorted Set 'test-sorted-set' was not found in cache 'test-cache'")
{:error, error} ->
IO.puts(
"An error occurred while attempting to fetch by score on sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}"
)
raise error
end
SortedSetGetScore
Gets an element's score from the sorted set, indexed by value.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
setName | String | Name of the sorted set collection. |
value | String | Bytes | The 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.
- JavaScript
- Rust
- Elixir
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()}`
);
}
let _score: f64 = cache_client
.sorted_set_get_score(cache_name, "sorted_set_name", "value1")
.await?
.try_into()
.expect("Expected a score!");
{:ok, _} =
Momento.CacheClient.sorted_set_put_elements(client, "test-cache", "test-sorted-set", [
{"key1", 10.0},
{"key2", 20.0}
])
case Momento.CacheClient.sorted_set_get_score(client, "test-cache", "test-sorted-set", "key1") do
{:ok, hit} ->
IO.puts("Element with value 'key1' has score: #{hit.score}")
:miss ->
IO.puts(
"Value 'key1' not found in sorted set, or sorted set 'test-sorted-set' was not found in cache 'test-cache'"
)
{:error, error} ->
IO.puts(
"An error occurred while attempting to get the score of 'key1' in sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}"
)
raise error
end
SortedSetGetScores
Gets the scores associated with a list of elements from the sorted set, indexed by value.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
setName | String | Name of the sorted set collection. |
values | String[] | 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
- Hit:
- Elements() (returns hit/miss per element)
- Cache miss (if the sorted set does not exist)
- Error
See response objects for specific information.
- JavaScript
- Elixir
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()}`
);
}
{:ok, _} =
Momento.CacheClient.sorted_set_put_elements(client, "test-cache", "test-sorted-set", [
{"key1", 10.0},
{"key2", 20.0}
])
case Momento.CacheClient.sorted_set_get_scores(client, "test-cache", "test-sorted-set", [
"key1",
"key2"
]) do
{:ok, hit} ->
IO.puts("Element scores retrieved successfully:")
IO.inspect(hit.value)
:miss ->
IO.puts("Sorted Set 'test-sorted-set' was not found in cache 'test-cache'")
{:error, error} ->
IO.puts(
"An error occurred while attempting to get the scores of values in sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}"
)
raise error
end
SortedSetRemoveElement
Removes an element from a sorted set, indexed by value.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
setName | String | Name of the set collection to be altered. |
value | String | Bytes | Value of the element to be removed by this operation. |
Method response object
- Success
- Error
See response objects for specific information.
- JavaScript
- Elixir
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()}`
);
}
{:ok, _} =
Momento.CacheClient.sorted_set_put_element(
client,
"test-cache",
"test-sorted-set",
"key1",
10.0
)
case Momento.CacheClient.sorted_set_remove_element(
client,
"test-cache",
"test-sorted-set",
"key1"
) do
{:ok, _} ->
IO.puts("Element with value 'key1' removed successfully")
{:error, error} ->
IO.puts(
"An error occurred while attempting to remove value 'key1' from sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}"
)
raise error
end
SortedSetRemoveElements
Removes elements from a sorted set, indexed by values.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
setName | String | Name of the set collection to be altered. |
values | String[] | 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.
- JavaScript
- Rust
- Elixir
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()}`
);
}
cache_client
.sorted_set_remove_elements(cache_name, "sorted_set_name", vec!["value1", "value2"])
.await?;
println!("Elements removed from sorted set");
{:ok, _} =
Momento.CacheClient.sorted_set_put_elements(client, "test-cache", "test-sorted-set", [
{"key1", 10.0},
{"key2", 20.0}
])
case Momento.CacheClient.sorted_set_remove_elements(client, "test-cache", "test-sorted-set", [
"key1",
"key2"
]) do
{:ok, _} ->
IO.puts("Elements with value 'key1' and 'key2' removed successfully")
{:error, error} ->
IO.puts(
"An error occurred while attempting remove values from sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}"
)
raise error
end
SortedSetGetRank
What position is the element, in the specified sorted set?
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
setName | String | Name of the sorted set collection to be altered. |
value | String | Bytes | Value of the element to retrieve the score of. |
order | Optional[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.
- JavaScript
- Rust
- Elixir
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()}`
);
}
let _rank: u64 = cache_client
.sorted_set_get_rank(cache_name, "sorted_set_name", "value1")
.await?
.try_into()
.expect("Expected a rank!");
{:ok, _} =
Momento.CacheClient.sorted_set_put_elements(client, "test-cache", "test-sorted-set", [
{"key1", 10.0},
{"key2", 20.0}
])
case Momento.CacheClient.sorted_set_get_rank(client, "test-cache", "test-sorted-set", "key1") do
{:ok, hit} ->
IO.puts("Element with value 'key1' has rank: #{hit.rank}")
:miss ->
IO.puts(
"Value 'key1' not found in sorted set, or sorted set 'test-sorted-set' was not found in cache 'test-cache'"
)
{:error, error} ->
IO.puts(
"An error occurred while attempting to get the rank of 'key1' in sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}"
)
raise error
end
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.
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.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
setName | String | Name of the sorted set collection to be altered. |
value | String | Bytes | Value for the element to be incremented by this operation. |
amount | Number | The quantity to add to the score. May be positive, negative, or zero. Defaults to 1. |
ttl | CollectionTTL object | TTL 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.
- JavaScript
- Elixir
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()}`
);
}
case Momento.CacheClient.sorted_set_increment_score(
client,
"test-cache",
"test-sorted-set",
"key1",
1
) do
{:ok, result} ->
IO.puts("Score for value 'key1' incremented successfully. New score: #{result.score}")
{:error, error} ->
IO.puts(
"An error occurred while attempting to increment the score of 'key1' in sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}"
)
raise error
end
SortedSetElement
A value and score makes up each element in a sorted set.
Example:
{ "TomHocusXaster" : 1138 }
Name | Type | Description |
---|---|---|
Value | String | Bytes | Value for the sorted set element. |
Score | Signed double 64-bit float | Score 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.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
sortedSetName | String | Name of the sorted set collection to be checked. |
Method response object
- Hit
length()
: Number
- Miss
- Error
See response objects for specific information.
- Rust
let _length: u32 = cache_client
.sorted_set_length(cache_name, "sorted_set_name")
.await?
.try_into()
.expect("Expected a list length!");
SortedSetLengthByScore
For an existing sorted set collection, it finds all of the values between the specified min and max score and returns the length.
Name | Type | Description |
---|---|---|
cacheName | String | Name of the cache. |
sortedSetName | String | Name of the sorted set collection to be checked. |
minScore | Optional[double] | The inclusive low score of the results. Default is -inf , ie include through the lowest score. |
maxScore | Optional[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.