Skip to main content

API reference for Momento Cache

Control APIs

These API methods are used to manage and control caches.

Create cache

Creates a cache with the provided name

Attributes:

NameTypeDescription
cacheNameStringName of the cache to be created.
const result = await cacheClient.createCache(cacheName);
switch (result.type) {
case CreateCacheResponse.AlreadyExists:
console.log(`Cache '${cacheName}' already exists`);
break;
case CreateCacheResponse.Success:
console.log(`Cache '${cacheName}' created`);
break;
case CreateCacheResponse.Error:
throw new Error(
`An error occurred while attempting to create cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Delete cache

Deletes a cache

Attributes:

NameTypeDescription
cacheNameStringName of the cache to be deleted.
const result = await cacheClient.deleteCache(cacheName);
switch (result.type) {
case DeleteCacheResponse.Success:
console.log(`Cache '${cacheName}' deleted`);
break;
case DeleteCacheResponse.Error:
throw new Error(
`An error occurred while attempting to delete cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

List caches

Lists all caches

const result = await cacheClient.listCaches();
switch (result.type) {
case ListCachesResponse.Success:
console.log(
`Caches:\n${result
.getCaches()
.map(c => c.getName())
.join('\n')}\n\n`
);
break;
case ListCachesResponse.Error:
throw new Error(`An error occurred while attempting to list caches: ${result.errorCode()}: ${result.toString()}`);
}

Flush cache

Flushes all data from a cache

Attributes:

NameTypeDescription
cacheNameStringName of the cache to be flushed.
const result = await cacheClient.flushCache(cacheName);
switch (result.type) {
case FlushCacheResponse.Success:
console.log(`Cache '${cacheName}' flushed`);
break;
case FlushCacheResponse.Error:
throw new Error(
`An error occurred while attempting to flush cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
tip

While you could use Delete Cache, then Create Cache to mimic this, the FlushCache API keeps the settings and only deletes the data in the cache.

Data APIs

These API methods are used to directly interact with data in a cache.

Set

Sets the value in cache with a given Time To Live (TTL) seconds. If a value for this key is already present, it will be replaced by the new value regardless of the previous value's data type.

NameTypeDescription
cacheNameStringName of the cache.
key[]ByteThe key under which the value is to be added.
value[]ByteThe value to be stored.
ttlSecondsintTime to Live for the item in Cache.
const result = await cacheClient.set(cacheName, 'test-key', 'test-value');
switch (result.type) {
case CacheSetResponse.Success:
console.log("Key 'test-key' stored successfully");
break;
case CacheSetResponse.Error:
throw new Error(
`An error occurred while attempting to store key 'test-key' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

SetBatch

Sets multiple key-value pairs in a cache with a given Time To Live (TTL) seconds. If a value for a key is already present, it will be replaced by the new value regardless of the previous value's data type.

NameTypeDescription
cacheNameStringName of the cache.
items{ String/[]Byte : String/[]Byte }The mapping of keys to values that should be stored
ttlSecondsintTime to Live for the items in Cache.
const values = new Map<string, string>([
['abc', '123'],
['xyz', '321'],
['123', 'xyz'],
['321', 'abc'],
]);
const result = await cacheClient.setBatch(cacheName, values);
switch (result.type) {
case CacheSetBatchResponse.Success:
console.log('Keys and values stored successfully');
break;
case CacheSetBatchResponse.Error:
throw new Error(
`An error occurred while attempting to batch set in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
Method response object
  • Success
  • results(): CacheSet.Response[]
  • Error

Get

Get the cache value stored for the given key.

NameTypeDescription
cacheNameStringName of the cache.
key[]ByteThe key under which the value is to be retrieved.
const getResponse = await cacheClient.get(cacheName, 'test-key');
// simplified style; assume the value was found
console.log(`cache hit: ${getResponse.value()!}`);

// pattern-matching style; safer for production code
switch (getResponse.type) {
case CacheGetResponse.Hit:
console.log(`Retrieved value for key 'test-key': ${getResponse.valueString()}`);
break;
case CacheGetResponse.Miss:
console.log(`Key 'test-key' was not found in cache '${cacheName}'`);
break;
case CacheGetResponse.Error:
throw new Error(
`An error occurred while attempting to get key 'test-key' from cache '${cacheName}': ${getResponse.errorCode()}: ${getResponse.toString()}`
);
}

GetBatch

Get the cache values stored for the given keys.

NameTypeDescription
cacheNameStringName of the cache.
keysString[] / Bytes[]The list of keys for which to retrieve values.
const keys = ['abc', 'xyz', '123', '321'];
const getBatchResponse = await cacheClient.getBatch(cacheName, keys);

// simplified style; assume the value was found
const values = getBatchResponse.values()!;
for (const key of keys) {
console.log(`Retrieved value for key '${key}': ${values[key]}`);
}

// pattern-matching style; safer for production code
switch (getBatchResponse.type) {
case CacheGetBatchResponse.Success: {
const values = getBatchResponse.values();
for (const key of keys) {
console.log(`Retrieved value for key '${key}': ${values[key]}`);
}
break;
}
case CacheGetBatchResponse.Error:
throw new Error(
`An error occurred while attempting to batch get in cache '${cacheName}': ${getBatchResponse.errorCode()}: ${getBatchResponse.toString()}`
);
}
Method response object
  • Success
  • values(): Record<string, string>
  • results(): CacheGet.Response[]
  • Error

Delete

Delete the cache value stored for the given key.

NameTypeDescription
cacheNameStringName of the cache.
key[]ByteThe key under which the value is to be deleted.
const result = await cacheClient.delete(cacheName, 'test-key');
switch (result.type) {
case CacheDeleteResponse.Success:
console.log("Key 'test-key' deleted successfully");
break;
case CacheDeleteResponse.Error:
throw new Error(
`An error occurred while attempting to delete key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Increment

Adds to the value of an item, if and only if the existing value is a UTF-8 string representing a base 10 integer. If the item does not exist, this method sets the item's value to the amount to increment by.

NameTypeDescription
cacheNameStringName of the cache.
keyStringThe key under which the value is to be incremented.
amountIntegerThe quantity to add to the value. May be positive, negative, or zero. Defaults to 1.
note

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

await cacheClient.set(cacheName, 'test-key', '10');
const result = await cacheClient.increment(cacheName, 'test-key', 1);
switch (result.type) {
case CacheIncrementResponse.Success:
console.log(`Key 'test-key' incremented successfully. New value in key test-key: ${result.valueNumber()}`);
break;
case CacheIncrementResponse.Error:
throw new Error(
`An error occurred while attempting to increment the value of key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Ping

Sends a ping to the server. This API can be used for checking connectivity to confirm that the client can connect to the server successfully.

Method response object
  • Success
  • Error

See response objects for specific information.

ItemGetType

For a given key, returns the type (SCALAR, DICTIONARY, LIST, etc.) of the corresponding item, if it exists.

NameTypeDescription
cacheNameStringName of the cache.
keyString | ByteKey whose item type should be returned.
Method response object
  • Cache hit
  • type(): enum: SCALAR, DICTIONARY, SET, LIST, SORTED_SET
  • Cache miss
  • Cache error

See response objects for specific information.

const result = await cacheClient.itemGetType(cacheName, 'test-key');
switch (result.type) {
case CacheItemGetTypeResponse.Hit:
console.log(`Item type retrieved successfully: ${ItemType[result.itemType()]}`);
break;
case CacheItemGetTypeResponse.Miss:
console.log("Key 'test-key' was not found in cache '${cacheName}'");
break;
case CacheItemGetTypeResponse.Error:
throw new Error(
`An error occurred while attempting to get the type of key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

KeyExists

Checks if a provided key exists in the cache.

NameTypeDescription
cacheNameStringName of the cache.
keyString | ByteKey which is to be checked for its existence in the cache.
Method response object
  • Success
  • exists(): Bool
  • Error

See response objects for specific information.

const result = await cacheClient.keyExists(cacheName, 'test-key');
switch (result.type) {
case CacheKeyExistsResponse.Success:
console.log("Does 'test-key' exist in the cache?", result.exists());
break;
case CacheKeyExistsResponse.Error:
throw new Error(
`An error occurred while attempting to call keyExists on key 'test-key' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

KeysExist

Checks if provided keys exist in the cache.

NameTypeDescription
cacheNameStringName of the cache.
keysString[] | Byte[]Keys which are to be checked for their existence in the cache.
Method response object
  • Success
  • exists(): Bool[]
  • Error

See response objects for specific information.

const result = await cacheClient.keysExist(cacheName, ['test-key1', 'test-key2']);
switch (result.type) {
case CacheKeysExistResponse.Success:
console.log("Do 'test-key1' and 'test-key2' exist in the cache?", result.exists());
break;
case CacheKeysExistResponse.Error:
throw new Error(
`An error occurred while attempting to call keysExist on keys 'test-key1' and 'test-key2' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

SetIfAbsent

warning

Do NOT use check-and-set (CAS) APIs such as SetIfPresent with scalar or non-CAS APIs such as Set or Delete. Doing so will result in undefined consistency behaviors. Use SetIfAbsent instead with SetIfPresent.

Associates the provided value to a cache item with a given key if the key does not already exist in the cache.

NameTypeDescription
cacheNameStringName of the cache.
keyString | BytesThe key to be set.
valueString | BytesThe value to be stored.
ttlSecondsDurationTime to Live for the item in Cache.
Method response object
  • Stored
  • NotStored
  • Error

See response objects for specific information.

const result = await cacheClient.setIfAbsent(cacheName, 'test-key', 'test-field');
switch (result.type) {
case CacheSetIfAbsentResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfAbsentResponse.NotStored:
console.log(`Key 'test-key' already exists in cache ${cacheName}, so we did not overwrite it`);
break;
case CacheSetIfAbsentResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfAbsent for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

SetIfPresent

warning

Do NOT use check-and-set (CAS) APIs such as SetIfPresent with scalar or non-CAS APIs such as Set or Delete. Doing so will result in undefined consistency behaviors. Use SetIfAbsent instead with SetIfPresent.

Associates the provided value to a cache item with a given key if the key already exists in the cache.

NameTypeDescription
cacheNameStringName of the cache.
keyString | BytesThe key to be set.
valueString | BytesThe value to be stored.
ttlSecondsDurationTime to Live for the item in Cache.
Method response object
  • Stored
  • NotStored
  • Error

See response objects for specific information.

const result = await cacheClient.setIfPresent(cacheName, 'test-key', 'test-field');
switch (result.type) {
case CacheSetIfPresentResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfPresentResponse.NotStored:
console.log(`Key 'test-key' does not exist in cache ${cacheName}, so we did not set the field`);
break;
case CacheSetIfPresentResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfPresent for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

SetIfEqual

warning

Do NOT use check-and-set (CAS) APIs such as SetIfEqual with scalar or non-CAS APIs such as Set or Delete. Doing so will result in undefined consistency behaviors. Use SetIfNotEqual instead with SetIfEqual.

Associates the provided value to a cache item with a given key if the key already exists in the cache and the value in the cache is equal to the value supplied for equal.

NameTypeDescription
cacheNameStringName of the cache.
keyString | BytesThe key to be set.
valueString | BytesThe value to be stored.
equalString | BytesThe value to compare with.
ttlSecondsDurationTime to Live for the item in Cache.
Method response object
  • Stored
  • NotStored
  • Error

See response objects for specific information.

const result = await cacheClient.setIfEqual(cacheName, 'test-key', 'test-field', 'value-to-check');
switch (result.type) {
case CacheSetIfEqualResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfEqualResponse.NotStored:
console.log("Value of key 'test-key' does not equal 'value-to-check', so we did not set the field");
break;
case CacheSetIfEqualResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfEqual for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

SetIfNotEqual

warning

Do NOT use check-and-set (CAS) APIs such as SetIfNotEqual with scalar or non-CAS APIs such as Set or Delete. Doing so will result in undefined consistency behaviors. Use SetIfEqual instead with SetIfNotEqual.

Associates the provided value to a cache item with a given key if the key does not already exist in the cache or the value in the cache is not equal to the value supplied for notEqual.

NameTypeDescription
cacheNameStringName of the cache.
keyString | BytesThe key to be set.
valueString | BytesThe value to be stored.
notEqualString | BytesThe value to compare with.
ttlSecondsDurationTime to Live for the item in Cache.
Method response object
  • Stored
  • NotStored
  • Error

See response objects for specific information.

const result = await cacheClient.setIfNotEqual(cacheName, 'test-key', 'test-field', 'value-to-check');
switch (result.type) {
case CacheSetIfNotEqualResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfNotEqualResponse.NotStored:
console.log("Value of key 'test-key' equals 'value-to-check', so we did not set the field");
break;
case CacheSetIfNotEqualResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfNotEqual for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

SetIfPresentAndNotEqual

warning

Do NOT use check-and-set (CAS) APIs such as SetIfPresentAndNotEqual with scalar or non-CAS APIs such as Set or Delete. Doing so will result in undefined consistency behaviors. Use SetIfAbsentOrEqual instead with SetIfPresentAndNotEqual.

Associates the provided value to a cache item with a given key if the key already exists in the cache and the value in the cache is not equal to the value supplied for notEqual.

NameTypeDescription
cacheNameStringName of the cache.
keyString | BytesThe key to be set.
valueString | BytesThe value to be stored.
notEqualString | BytesThe value to compare with.
ttlSecondsDurationTime to Live for the item in Cache.
Method response object
  • Stored
  • NotStored
  • Error

See response objects for specific information.

const result = await cacheClient.setIfPresentAndNotEqual(cacheName, 'test-key', 'test-field', 'value-to-check');
switch (result.type) {
case CacheSetIfPresentAndNotEqualResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfPresentAndNotEqualResponse.NotStored:
console.log(
`Key 'test-key' does not exist in cache ${cacheName} or equals 'value-to-check', so we did not set the field`
);
break;
case CacheSetIfPresentAndNotEqualResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfPresentAndNotEqual for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

SetIfAbsentOrEqual

warning

Do NOT use check-and-set (CAS) APIs such as SetIfAbsentOrEqual with scalar or non-CAS APIs such as Set or Delete. Doing so will result in undefined consistency behaviors. Use SetIfPresentAndNotEqual instead with SetIfAbsentOrEqual.

Associates the provided value to a cache item with a given key if the key does not already exist in the cache or the value in the cache is equal to the value supplied for equal.

NameTypeDescription
cacheNameStringName of the cache.
keyString | BytesThe key to be set.
valueString | BytesThe value to be stored.
equalString | BytesThe value to compare with.
ttlSecondsDurationTime to Live for the item in Cache.
Method response object
  • Stored
  • NotStored
  • Error

See response objects for specific information.

const result = await cacheClient.setIfAbsentOrEqual(cacheName, 'test-key', 'test-field', 'value-to-check');
switch (result.type) {
case CacheSetIfAbsentOrEqualResponse.Stored:
console.log("Field 'test-field' set in key 'test-key'");
break;
case CacheSetIfAbsentOrEqualResponse.NotStored:
console.log(
`Key 'test-key' exists in cache ${cacheName} and is not equal to 'value-to-check', so we did not set the field`
);
break;
case CacheSetIfAbsentOrEqualResponse.Error:
throw new Error(
`An error occurred while attempting to call setIfAbsentOrEqual for the key 'test-key' in cache cacheName: ${result.errorCode()}: ${result.toString()}`
);
}

Time to Live APIs

These APIs apply across all cache types.

UpdateTtl

Overwrites the TTL of a cache item with the provided value in seconds.

NameTypeDescription
cacheNameStringName of the cache.
keyString | BytesThe key under which the value's TTL is to be updated.
ttlDurationTime to live that you want to update in cache in seconds.
resp, err := client.UpdateTtl(ctx, &momento.UpdateTtlRequest{
CacheName: cacheName,
Key: momento.String("key"),
Ttl: time.Duration(9999),
})
if err != nil {
panic(err)
}
switch resp.(type) {
case *responses.UpdateTtlSet:
log.Printf("Successfully updated TTL for key\n")
case *responses.UpdateTtlMiss:
log.Printf("Key does not exist in cache\n")
}

IncreaseTtl

Increase the TTL seconds for a key to the provided value only if it would increase the TTL.

Examples

  • If the TTL is 5 seconds and is increased to 6 seconds, the new TTL will be 6 seconds.
  • If the TTL is 5 seconds and is increased to 3 seconds, the TTL will not be increased.
NameTypeDescription
cacheNameStringName of the cache.
keyString | BytesThe key under which the value's TTL is to be increased.
ttlDurationTime to live that you want to increase to.
resp, err := client.IncreaseTtl(ctx, &momento.IncreaseTtlRequest{
CacheName: cacheName,
Key: momento.String("key"),
Ttl: time.Duration(9999),
})
if err != nil {
panic(err)
}
switch resp.(type) {
case *responses.IncreaseTtlSet:
log.Printf("Successfully increased TTL for key\n")
case *responses.IncreaseTtlMiss:
log.Printf("Key does not exist in cache\n")
}

DecreaseTtl

Decrease the TTL seconds for a key to the provided value only if it would decrease the TTL.

Examples

  • If the TTL is 5 seconds and is decreased to 3 seconds, the new TTL will be 3 seconds.
  • If the TTL is 5 seconds and is decreased to 6 seconds, the TTL will not be decreased.
NameTypeDescription
cacheNameStringName of the cache.
keyString | BytesThe key under which the value's TTL is to be decreased.
ttlDurationTime to live that you want to decrease to.
resp, err := client.DecreaseTtl(ctx, &momento.DecreaseTtlRequest{
CacheName: cacheName,
Key: momento.String("key"),
Ttl: time.Duration(9999),
})
if err != nil {
panic(err)
}
switch resp.(type) {
case *responses.DecreaseTtlSet:
log.Printf("Successfully decreased TTL for key\n")
case *responses.DecreaseTtlMiss:
log.Printf("Key does not exist in cache\n")
}

ItemGetTtl

For a given key, returns the duration of time remaining (Time To Live) before the item expires from the cache.

NameTypeDescription
cacheNameStringName of the cache.
keyString | ByteKey whose item type should be returned.
Method response object
  • Cache hit
  • remainingTtl(): Duration
  • Cache miss
  • Cache error

See response objects for specific information.

resp, err := client.ItemGetTtl(ctx, &momento.ItemGetTtlRequest{
CacheName: cacheName,
Key: momento.String("key"),
})
if err != nil {
panic(err)
}
switch r := resp.(type) {
case *responses.ItemGetTtlHit:
log.Printf("TTL for key is %d\n", r.RemainingTtl().Milliseconds())
case *responses.ItemGetTtlMiss:
log.Printf("Key does not exist in cache\n")
}

Collection data types

Collections may contain different types of structures depending on your use case. Supported data types are:

  • Dictionaries are used to store unordered field:value pairs.
  • Lists are a collection of ordered elements, sorted in the sequence each element was inserted.
  • Sets are an unordered collection of unique elements in string format.
  • Sorted Sets are an ordered collection of unique elements. Each element contains a value:score pair.

For more in-depth information on usage, see collection data types.

Current status of API support in SDKs

For the current status of API support in various SDK languages, see the language support page.