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);
if (result instanceof CreateCache.Success) {
console.log(`Cache '${cacheName}' created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache '${cacheName}' already exists`);
} else if (result instanceof CreateCache.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);
if (result instanceof DeleteCache.Success) {
console.log(`Cache '${cacheName}' deleted`);
} else if (result instanceof DeleteCache.Error) {
throw new Error(
`An error occurred while attempting to delete cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

List caches

Lists all caches

NameTypeDescription
nextTokenStringToken for pagination of caches.
const result = await cacheClient.listCaches();
if (result instanceof ListCaches.Success) {
console.log(
`Caches:\n${result
.getCaches()
.map(c => c.getName())
.join('\n')}\n\n`
);
} else if (result instanceof ListCaches.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);
if (result instanceof CacheFlush.Success) {
console.log(`Cache '${cacheName}' flushed`);
} else if (result instanceof CacheFlush.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.

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');
if (result instanceof CacheSet.Success) {
console.log("Key 'test-key' stored successfully");
} else if (result instanceof CacheSet.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.

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);
if (result instanceof SetBatch.Success) {
console.log('Keys and values stored successfully');
} else if (result instanceof SetBatch.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 result = await cacheClient.get(cacheName, 'test-key');
if (result instanceof CacheGet.Hit) {
console.log(`Retrieved value for key 'test-key': ${result.valueString()}`);
} else if (result instanceof CacheGet.Miss) {
console.log(`Key 'test-key' was not found in cache '${cacheName}'`);
} else if (result instanceof CacheGet.Error) {
throw new Error(
`An error occurred while attempting to get key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.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 result = await cacheClient.getBatch(cacheName, keys);
if (result instanceof GetBatch.Success) {
const values = result.values();
for (const key of keys) {
console.log(`Retrieved value for key '${key}': ${values[key]}`);
}
} else if (result instanceof GetBatch.Error) {
throw new Error(
`An error occurred while attempting to batch get in cache '${cacheName}': ${result.errorCode()}: ${result.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');
if (result instanceof CacheDelete.Success) {
console.log("Key 'test-key' deleted successfully");
} else if (result instanceof CacheDelete.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);
if (result instanceof CacheIncrement.Success) {
console.log(`Key 'test-key' incremented successfully. New value in key test-key: ${result.valueNumber()}`);
} else if (result instanceof CacheIncrement.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');
if (result instanceof CacheItemGetType.Hit) {
console.log(`Item type retrieved successfully: ${ItemType[result.itemType()]}`);
} else if (result instanceof CacheItemGetType.Miss) {
console.log("Key 'test-key' was not found in cache '${cacheName}'");
} else if (result instanceof CacheItemGetType.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');
if (result instanceof CacheKeyExists.Success) {
console.log("Does 'test-key' exists in the cache?", result.exists());
} else if (result instanceof CacheKeyExists.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']);
if (result instanceof CacheKeysExist.Success) {
console.log("Do 'test-key1' and 'test-key2' exist in the cache?", result.exists());
} else if (result instanceof CacheKeysExist.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()}`
);
}

SetIfNotExists

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.setIfNotExists(cacheName, 'test-key', 'test-field');
if (result instanceof CacheSetIfNotExists.Stored) {
console.log("Field 'test-field' set in key 'test-key'");
} else if (result instanceof CacheSetIfNotExists.NotStored) {
console.log(`Key 'test-key' already exists in cache '${cacheName}', so we did not overwrite it`);
} else if (result instanceof CacheSetIfNotExists.Error) {
throw new Error(
`An error occurred while attempting to call setIfNotExists for the key 'test-key' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

SetIfAbsent

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');
if (result instanceof CacheSetIfAbsent.Stored) {
console.log("Field 'test-field' set in key 'test-key'");
} else if (result instanceof CacheSetIfAbsent.NotStored) {
console.log(`Key 'test-key' already exists in cache ${cacheName}, so we did not overwrite it`);
} else if (result instanceof CacheSetIfAbsent.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

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');
if (result instanceof CacheSetIfPresent.Stored) {
console.log("Field 'test-field' set in key 'test-key'");
} else if (result instanceof CacheSetIfPresent.NotStored) {
console.log(`Key 'test-key' does not exist in cache ${cacheName}, so we did not set the field`);
} else if (result instanceof CacheSetIfPresent.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

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');
if (result instanceof CacheSetIfEqual.Stored) {
console.log("Field 'test-field' set in key 'test-key'");
} else if (result instanceof CacheSetIfEqual.NotStored) {
console.log("Value of key 'test-key' does not equal 'value-to-check', so we did not set the field");
} else if (result instanceof CacheSetIfEqual.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

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');
if (result instanceof CacheSetIfNotEqual.Stored) {
console.log("Field 'test-field' set in key 'test-key'");
} else if (result instanceof CacheSetIfNotEqual.NotStored) {
console.log("Value of key 'test-key' equals 'value-to-check', so we did not set the field");
} else if (result instanceof CacheSetIfNotEqual.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

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');
if (result instanceof CacheSetIfPresentAndNotEqual.Stored) {
console.log("Field 'test-field' set in key 'test-key'");
} else if (result instanceof CacheSetIfPresentAndNotEqual.NotStored) {
console.log(
`Key 'test-key' does not exist in cache ${cacheName} or equals 'value-to-check', so we did not set the field`
);
} else if (result instanceof CacheSetIfPresentAndNotEqual.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

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');
if (result instanceof CacheSetIfAbsentOrEqual.Stored) {
console.log("Field 'test-field' set in key 'test-key'");
} else if (result instanceof CacheSetIfAbsentOrEqual.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`
);
} else if (result instanceof CacheSetIfAbsentOrEqual.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: "cache-name",
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: "cache-name",
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: "cache-name",
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: "cache-name",
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.