Skip to content

Commit ecdd48f

Browse files
Merge pull request #88825 from ThomasWeiss/thweiss-cosmosdb-sdkv3-update
Added Cosmos DB .NET SDK V3 examples
2 parents 3be4026 + cbc213a commit ecdd48f

File tree

4 files changed

+273
-62
lines changed

4 files changed

+273
-62
lines changed

articles/cosmos-db/how-to-define-unique-keys.md

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ description: Learn how to define unique keys for an Azure Cosmos container
44
author: ThomasWeiss
55
ms.service: cosmos-db
66
ms.topic: conceptual
7-
ms.date: 05/23/2019
7+
ms.date: 09/17/2019
88
ms.author: thweiss
99
---
1010

@@ -38,17 +38,35 @@ When creating a new container using the [.NET SDK v2](https://www.nuget.org/pack
3838
client.CreateDocumentCollectionAsync(UriFactory.CreateDatabaseUri("database"), new DocumentCollection
3939
{
4040
Id = "container",
41+
PartitionKey = new PartitionKeyDefinition { Paths = new Collection<string>(new List<string> { "/myPartitionKey" }) },
4142
UniqueKeyPolicy = new UniqueKeyPolicy
4243
{
4344
UniqueKeys = new Collection<UniqueKey>(new List<UniqueKey>
4445
{
45-
new UniqueKey { Paths = new Collection<string>(new List<string> { "/firstName", "/lastName", "emailAddress" }) },
46+
new UniqueKey { Paths = new Collection<string>(new List<string> { "/firstName", "/lastName", "/emailAddress" }) },
4647
new UniqueKey { Paths = new Collection<string>(new List<string> { "/address/zipCode" }) }
4748
})
4849
}
4950
});
5051
```
5152

53+
## Use the .NET SDK V3
54+
55+
When creating a new container using the [.NET SDK v3](https://www.nuget.org/packages/Microsoft.Azure.Cosmos/), use the SDK's fluent API to declare unique keys in a concise and readable way.
56+
57+
```csharp
58+
await client.GetDatabase("database").DefineContainer(name: "container", partitionKeyPath: "/myPartitionKey")
59+
.WithUniqueKey()
60+
.Path("/firstName")
61+
.Path("/lastName")
62+
.Path("/emailAddress")
63+
.Attach()
64+
.WithUniqueKey()
65+
.Path("/address/zipCode")
66+
.Attach()
67+
.CreateIfNotExistsAsync();
68+
```
69+
5270
## Use the Java SDK
5371

5472
When creating a new container using the [Java SDK](https://mvnrepository.com/artifact/com.microsoft.azure/azure-cosmosdb), a `UniqueKeyPolicy` object can be used to define unique key constraints.

articles/cosmos-db/how-to-manage-indexing-policy.md

Lines changed: 63 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ description: Learn how to manage indexing policies in Azure Cosmos DB
44
author: ThomasWeiss
55
ms.service: cosmos-db
66
ms.topic: conceptual
7-
ms.date: 09/10/2019
7+
ms.date: 09/17/2019
88
ms.author: thweiss
99
---
1010

@@ -369,57 +369,91 @@ az cosmosdb collection update \
369369

370370
## Use the .NET SDK V2
371371

372-
The `DocumentCollection` object from the [.NET SDK v2](https://www.nuget.org/packages/Microsoft.Azure.DocumentDB/) (see [this Quickstart](create-sql-api-dotnet.md) regarding its usage) exposes an `IndexingPolicy` property that lets you change the `IndexingMode` and add or remove `IncludedPaths` and `ExcludedPaths`.
372+
The `DocumentCollection` object from the [.NET SDK v2](https://www.nuget.org/packages/Microsoft.Azure.DocumentDB/) exposes an `IndexingPolicy` property that lets you change the `IndexingMode` and add or remove `IncludedPaths` and `ExcludedPaths`.
373373

374-
Retrieve the container's details
375374

376375
```csharp
376+
// Retrieve the container's details
377377
ResourceResponse<DocumentCollection> containerResponse = await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri("database", "container"));
378-
```
379-
380-
Set the indexing mode to consistent
381-
382-
```csharp
378+
// Set the indexing mode to consistent
383379
containerResponse.Resource.IndexingPolicy.IndexingMode = IndexingMode.Consistent;
380+
// Add an included path
381+
containerResponse.Resource.IndexingPolicy.IncludedPaths.Add(new IncludedPath { Path = "/*" });
382+
// Add an excluded path
383+
containerResponse.Resource.IndexingPolicy.ExcludedPaths.Add(new ExcludedPath { Path = "/name/*" });
384+
// Add a spatial index
385+
containerResponse.Resource.IndexingPolicy.SpatialIndexes.Add(new SpatialSpec() { Path = "/locations/*", SpatialTypes = new Collection<SpatialType>() { SpatialType.Point } } );
386+
// Add a composite index
387+
containerResponse.Resource.IndexingPolicy.CompositeIndexes.Add(new Collection<CompositePath> {new CompositePath() { Path = "/name", Order = CompositePathSortOrder.Ascending }, new CompositePath() { Path = "/age", Order = CompositePathSortOrder.Descending }});
388+
// Update container with changes
389+
await client.ReplaceDocumentCollectionAsync(containerResponse.Resource);
384390
```
385391

386-
Add an included path
387-
388-
```csharp
389-
containerResponse.Resource.IndexingPolicy.IncludedPaths.Add(new IncludedPath { Path = "/age/*" });
390-
```
391-
392-
Add an excluded path
392+
To track the index transformation progress, pass a `RequestOptions` object that sets the `PopulateQuotaInfo` property to `true`.
393393

394394
```csharp
395-
containerResponse.Resource.IndexingPolicy.ExcludedPaths.Add(new ExcludedPath { Path = "/name/*" });
395+
// retrieve the container's details
396+
ResourceResponse<DocumentCollection> container = await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri("database", "container"), new RequestOptions { PopulateQuotaInfo = true });
397+
// retrieve the index transformation progress from the result
398+
long indexTransformationProgress = container.IndexTransformationProgress;
396399
```
397400

398-
Add a spatial index
401+
## Use the .NET SDK V3
399402

400-
```csharp
401-
containerResponse.Resource.IndexingPolicy.SpatialIndexes.Add(new SpatialSpec() { Path = "/locations/*", SpatialTypes = new Collection<SpatialType>() { SpatialType.Point } } );
402-
```
403+
The `ContainerProperties` object from the [.NET SDK v3](https://www.nuget.org/packages/Microsoft.Azure.Cosmos/) (see [this Quickstart](create-sql-api-dotnet.md) regarding its usage) exposes an `IndexingPolicy` property that lets you change the `IndexingMode` and add or remove `IncludedPaths` and `ExcludedPaths`.
403404

404-
Add a composite index
405405

406406
```csharp
407-
containerResponse.Resource.IndexingPolicy.CompositeIndexes.Add(new Collection<CompositePath> {new CompositePath() { Path = "/name", Order = CompositePathSortOrder.Ascending }, new CompositePath() { Path = "/age", Order = CompositePathSortOrder.Descending }});
407+
// Retrieve the container's details
408+
ContainerResponse containerResponse = await client.GetContainer("database", "container").ReadContainerAsync();
409+
// Set the indexing mode to consistent
410+
containerResponse.Resource.IndexingPolicy.IndexingMode = IndexingMode.Consistent;
411+
// Add an included path
412+
containerResponse.Resource.IndexingPolicy.IncludedPaths.Add(new IncludedPath { Path = "/*" });
413+
// Add an excluded path
414+
containerResponse.Resource.IndexingPolicy.ExcludedPaths.Add(new ExcludedPath { Path = "/name/*" });
415+
// Add a spatial index
416+
SpatialPath spatialPath = new SpatialPath
417+
{
418+
Path = "/locations/*"
419+
};
420+
spatialPath.SpatialTypes.Add(SpatialType.Point);
421+
containerResponse.Resource.IndexingPolicy.SpatialIndexes.Add(spatialPath);
422+
// Add a composite index
423+
containerResponse.Resource.IndexingPolicy.CompositeIndexes.Add(new Collection<CompositePath> { new CompositePath() { Path = "/name", Order = CompositePathSortOrder.Ascending }, new CompositePath() { Path = "/age", Order = CompositePathSortOrder.Descending } });
424+
// Update container with changes
425+
await client.GetContainer("database", "container").ReplaceContainerAsync(containerResponse.Resource);
408426
```
409427

410-
Update container with changes
428+
To track the index transformation progress, pass a `RequestOptions` object that sets the `PopulateQuotaInfo` property to `true`, then retrieve the value from the `x-ms-documentdb-collection-index-transformation-progress` response header.
411429

412430
```csharp
413-
await client.ReplaceDocumentCollectionAsync(containerResponse.Resource);
431+
// retrieve the container's details
432+
ContainerResponse containerResponse = await client.GetContainer("database", "container").ReadContainerAsync(new ContainerRequestOptions { PopulateQuotaInfo = true });
433+
// retrieve the index transformation progress from the result
434+
long indexTransformationProgress = long.Parse(containerResponse.Headers["x-ms-documentdb-collection-index-transformation-progress"]);
414435
```
415436

416-
To track the index transformation progress, pass a `RequestOptions` object that sets the `PopulateQuotaInfo` property to `true`.
437+
When defining a custom indexing policy while creating a new container, the SDK V3's fluent API lets you write this definition in a concise and efficient way:
417438

418439
```csharp
419-
// retrieve the container's details
420-
ResourceResponse<DocumentCollection> container = await client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri("database", "container"), new RequestOptions { PopulateQuotaInfo = true });
421-
// retrieve the index transformation progress from the result
422-
long indexTransformationProgress = container.IndexTransformationProgress;
440+
await client.GetDatabase("database").DefineContainer(name: "container", partitionKeyPath: "/myPartitionKey")
441+
.WithIndexingPolicy()
442+
.WithIncludedPaths()
443+
.Path("/*")
444+
.Attach()
445+
.WithExcludedPaths()
446+
.Path("/name/*")
447+
.Attach()
448+
.WithSpatialIndex()
449+
.Path("/locations/*", SpatialType.Point)
450+
.Attach()
451+
.WithCompositeIndex()
452+
.Path("/name", CompositePathSortOrder.Ascending)
453+
.Path("/age", CompositePathSortOrder.Descending)
454+
.Attach()
455+
.Attach()
456+
.CreateIfNotExistsAsync();
423457
```
424458

425459
## Use the Java SDK

articles/cosmos-db/how-to-time-to-live.md

Lines changed: 70 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ description: Learn how to configure and manage time to live in Azure Cosmos DB
44
author: markjbrown
55
ms.service: cosmos-db
66
ms.topic: conceptual
7-
ms.date: 05/23/2019
7+
ms.date: 09/17/2019
88
ms.author: mjbrown
99
---
1010

@@ -38,38 +38,60 @@ Use the following steps to enable time to live on a container with no expiration
3838

3939
## Enable time to live on a container using SDK
4040

41-
### <a id="dotnet-enable-noexpiry"></a>.NET SDK
41+
### <a id="dotnet-enable-noexpiry"></a>.NET SDK V2 (Microsoft.Azure.DocumentDB)
4242

4343
```csharp
44-
// Create a new collection with TTL enabled and without any expiration value
44+
// Create a new container with TTL enabled and without any expiration value
4545
DocumentCollection collectionDefinition = new DocumentCollection();
4646
collectionDefinition.Id = "myContainer";
4747
collectionDefinition.PartitionKey.Paths.Add("/myPartitionKey");
4848
collectionDefinition.DefaultTimeToLive = -1; //(never expire by default)
4949
5050
DocumentCollection ttlEnabledCollection = await client.CreateDocumentCollectionAsync(
5151
UriFactory.CreateDatabaseUri("myDatabaseName"),
52-
collectionDefinition,
53-
new RequestOptions { OfferThroughput = 20000 });
52+
collectionDefinition);
5453
```
5554

56-
## Set time to live on a container using SDK
55+
### <a id="dotnet-enable-noexpiry"></a>.NET SDK V3 (Microsoft.Azure.Cosmos)
56+
57+
```csharp
58+
// Create a new container with TTL enabled and without any expiration value
59+
await client.GetDatabase("database").CreateContainerAsync(new ContainerProperties
60+
{
61+
Id = "container",
62+
PartitionKeyPath = "/myPartitionKey",
63+
DefaultTimeToLive = -1 //(never expire by default)
64+
});
65+
```
5766

58-
### <a id="dotnet-enable-withexpiry"></a>.NET SDK
67+
## Set time to live on a container using SDK
5968

6069
To set the time to live on a container, you need to provide a non-zero positive number that indicates the time period in seconds. Based on the configured TTL value, all items in the container after the last modified timestamp of the item `_ts` are deleted.
6170

71+
### <a id="dotnet-enable-withexpiry"></a>.NET SDK V2 (Microsoft.Azure.DocumentDB)
72+
6273
```csharp
63-
// Create a new collection with TTL enabled and a 90 day expiration
74+
// Create a new container with TTL enabled and a 90 day expiration
6475
DocumentCollection collectionDefinition = new DocumentCollection();
6576
collectionDefinition.Id = "myContainer";
6677
collectionDefinition.PartitionKey.Paths.Add("/myPartitionKey");
6778
collectionDefinition.DefaultTimeToLive = 90 * 60 * 60 * 24; // expire all documents after 90 days
6879
6980
DocumentCollection ttlEnabledCollection = await client.CreateDocumentCollectionAsync(
7081
UriFactory.CreateDatabaseUri("myDatabaseName"),
71-
collectionDefinition,
72-
new RequestOptions { OfferThroughput = 20000 });
82+
collectionDefinition;
83+
```
84+
85+
### <a id="dotnet-enable-withexpiry"></a>.NET SDK V3 (Microsoft.Azure.Cosmos)
86+
87+
```csharp
88+
// Create a new container with TTL enabled and a 90 day expiration
89+
await client.GetDatabase("database").CreateContainerAsync(new ContainerProperties
90+
{
91+
Id = "container",
92+
PartitionKeyPath = "/myPartitionKey",
93+
DefaultTimeToLive = 90 * 60 * 60 * 24; // expire all documents after 90 days
94+
});
7395
```
7496

7597
### <a id="nodejs-enable-withexpiry"></a>NodeJS SDK
@@ -127,7 +149,7 @@ Use the following steps to enable time to live on an item:
127149
}
128150
```
129151

130-
### <a id="dotnet-set-ttl-item"></a>.NET SDK
152+
### <a id="dotnet-set-ttl-item"></a>.NET SDK (any)
131153

132154
```csharp
133155
// Include a property that serializes to "ttl" in JSON
@@ -168,7 +190,7 @@ const itemDefinition = {
168190

169191
You can reset the time to live on an item by performing a write or update operation on the item. The write or update operation will set the `_ts` to the current time, and the TTL for the item to expire will begin again. If you wish to change the TTL of an item, you can update the field just as you update any other field.
170192

171-
### <a id="dotnet-extend-ttl-item"></a>.NET SDK
193+
### <a id="dotnet-extend-ttl-item"></a>.NET SDK V2 (Microsoft.Azure.DocumentDB)
172194

173195
```csharp
174196
// This examples leverages the Sales Order class above.
@@ -182,11 +204,22 @@ readDocument.ttl = 60 * 30 * 30; // update time to live
182204
response = await client.ReplaceDocumentAsync(readDocument);
183205
```
184206

207+
### <a id="dotnet-extend-ttl-item"></a>.NET SDK V3 (Microsoft.Azure.Cosmos)
208+
209+
```csharp
210+
// This examples leverages the Sales Order class above.
211+
// Read a document, update its TTL, save it.
212+
ItemResponse<SalesOrder> itemResponse = await client.GetContainer("database", "container").ReadItemAsync<SalesOrder>("SO05", new PartitionKey("CO18009186470"));
213+
214+
itemResponse.Resource.ttl = 60 * 30 * 30; // update time to live
215+
await client.GetContainer("database", "container").ReplaceItemAsync(itemResponse.Resource, "SO05");
216+
```
217+
185218
## Turn off time to live
186219

187220
If time to live has been set on an item and you no longer want that item to expire, then you can get the item, remove the TTL field, and replace the item on the server. When the TTL field is removed from the item, the default TTL value assigned to the container is applied to the item. Set the TTL value to -1 to prevent an item from expiring and to not inherit the TTL value from the container.
188221

189-
### <a id="dotnet-turn-off-ttl-item"></a>.NET SDK
222+
### <a id="dotnet-turn-off-ttl-item"></a>.NET SDK V2 (Microsoft.Azure.DocumentDB)
190223

191224
```csharp
192225
// This examples leverages the Sales Order class above.
@@ -196,25 +229,46 @@ response = await client.ReadDocumentAsync(
196229
new RequestOptions { PartitionKey = new PartitionKey("CO18009186470") });
197230

198231
Document readDocument = response.Resource;
199-
readDocument.ttl = null; // inherit the default TTL of the collection
232+
readDocument.ttl = null; // inherit the default TTL of the container
200233
201234
response = await client.ReplaceDocumentAsync(readDocument);
202235
```
203236

237+
### <a id="dotnet-turn-off-ttl-item"></a>.NET SDK V3 (Microsoft.Azure.Cosmos)
238+
239+
```csharp
240+
// This examples leverages the Sales Order class above.
241+
// Read a document, turn off its override TTL, save it.
242+
ItemResponse<SalesOrder> itemResponse = await client.GetContainer("database", "container").ReadItemAsync<SalesOrder>("SO05", new PartitionKey("CO18009186470"));
243+
244+
itemResponse.Resource.ttl = null; // inherit the default TTL of the container
245+
await client.GetContainer("database", "container").ReplaceItemAsync(itemResponse.Resource, "SO05");
246+
```
247+
204248
## Disable time to live
205249

206250
To disable time to live on a container and stop the background process from checking for expired items, the `DefaultTimeToLive` property on the container should be deleted. Deleting this property is different from setting it to -1. When you set it to -1, new items added to the container will live forever, however you can override this value on specific items in the container. When you remove the TTL property from the container the items will never expire, even if there are they have explicitly overridden the previous default TTL value.
207251

208-
### <a id="dotnet-disable-ttl"></a>.NET SDK
252+
### <a id="dotnet-disable-ttl"></a>.NET SDK V2 (Microsoft.Azure.DocumentDB)
209253

210254
```csharp
211-
// Get the collection, update DefaultTimeToLive to null
255+
// Get the container, update DefaultTimeToLive to null
212256
DocumentCollection collection = await client.ReadDocumentCollectionAsync("/dbs/salesdb/colls/orders");
213257
// Disable TTL
214258
collection.DefaultTimeToLive = null;
215259
await client.ReplaceDocumentCollectionAsync(collection);
216260
```
217261

262+
### <a id="dotnet-disable-ttl"></a>.NET SDK V3 (Microsoft.Azure.Cosmos)
263+
264+
```csharp
265+
// Get the container, update DefaultTimeToLive to null
266+
ContainerResponse containerResponse = await client.GetContainer("database", "container").ReadContainerAsync();
267+
// Disable TTL
268+
containerResponse.Resource.DefaultTimeToLive = null;
269+
await client.GetContainer("database", "container").ReplaceContainerAsync(containerResponse.Resource);
270+
```
271+
218272
## Next steps
219273

220274
Learn more about time to live in the following article:

0 commit comments

Comments
 (0)