Applications often have to deal with temporary data, such as: logs, user session information and others.
Purging that data can be a struggle especially when your database doesn’t support temporary storage.
With CosmosDb, developers are able to set Time To Live properties on Collections and Documents.
Example
Lets say you have a shopping cart in your application with which users can select items.
It doesn’t make sense to have those items indefinitely in your cart, lets say one week will be suffice.
Lets see how we can set the time to live to one week.
Create a collection with a default time to live
In order for time to live to be effective you have to set a default time to live on the collection. Setting it on documents alone will not work. You can also replace the collection and set it to null
to disable the time to live for the collection.
1 | await documentClient.CreateDatabaseIfNotExistsAsync(new Database() |
Once you’ve set the time to live on collections than every document will have that time to live as default. You can override it to prolong, shorten or disable the time to live for the selected document.
1 | // Set time to live |
Once a document is created in a time to live collection then a _ttl
property will be added to the document. Note that it doesn’t count down or something like that so you can’t see if a document is about to expire.
1 | { |
Hopefully this helped a little, for further reading please see:
https://docs.microsoft.com/en-us/azure/cosmos-db/time-to-live