Table of Contents

Class CosmosClient

Namespace
Microsoft.Azure.Cosmos
Assembly
Microsoft.Azure.Cosmos.Client.dll

Provides a client-side logical representation of the Azure Cosmos DB account. This client can be used to configure and execute requests in the Azure Cosmos DB database service.

CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. Please refer to the performance guide.

public class CosmosClient : IDisposable
Inheritance
CosmosClient
Implements
Inherited Members
Extension Methods

Examples

This example create a CosmosClient, Database, and a Container. The CosmosClient is created with the connection string and configured to use "East US 2" region.

using Microsoft.Azure.Cosmos;

CosmosClient cosmosClient = new CosmosClient(
            "connection-string-from-portal", 
            new CosmosClientOptions()
            {
                ApplicationRegion = Regions.EastUS2,
            });

Database db = await cosmosClient.CreateDatabaseAsync("database-id");
Container container = await db.CreateContainerAsync("container-id");

// Dispose cosmosClient at application exit

This example creates a CosmosClient, Database, and a Container. The CosmosClient is created with the AccountEndpoint, AccountKey or ResourceToken and configured to use "East US 2" region.

using Microsoft.Azure.Cosmos;

CosmosClient cosmosClient = new CosmosClient(
            "account-endpoint-from-portal", 
            "account-key-from-portal", 
            new CosmosClientOptions()
            {
                ApplicationRegion = Regions.EastUS2,
            });

Database db = await cosmosClient.CreateDatabaseAsync("database-id");
Container container = await db.CreateContainerAsync("container-id");

// Dispose cosmosClient at application exit

This example creates a CosmosClient, Database, and a Container. The CosmosClient is created through builder pattern using CosmosClientBuilder.

using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Fluent;

CosmosClient cosmosClient = new CosmosClientBuilder("connection-string-from-portal")
    .WithApplicationRegion("East US 2")
    .Build();

Database db = await cosmosClient.CreateDatabaseAsync("database-id")
Container container = await db.CreateContainerAsync("container-id");

// Dispose cosmosClient at application exit

Remarks

The returned not-initialized reference doesn't guarantee credentials or connectivity validations because creation doesn't make any network calls

Constructors

CosmosClient()

Create a new CosmosClient used for mock testing

protected CosmosClient()
See Also

CosmosClient(string, AzureKeyCredential, CosmosClientOptions)

Creates a new CosmosClient with the account endpoint URI string and AzureKeyCredential. AzureKeyCredential enables changing/updating master-key/ResourceToken while CosmosClient is still in use.

CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. Please refer to the performance guide.

public CosmosClient(string accountEndpoint, AzureKeyCredential authKeyOrResourceTokenCredential, CosmosClientOptions clientOptions = null)

Parameters

accountEndpoint string

The cosmos service endpoint to use

authKeyOrResourceTokenCredential AzureKeyCredential

AzureKeyCredential with master-key or resource token..

clientOptions CosmosClientOptions

(Optional) client options

Examples

The CosmosClient is created with the AccountEndpoint, AccountKey or ResourceToken and configured to use "East US 2" region.

using Microsoft.Azure.Cosmos;

AzureKeyCredential keyCredential = new AzureKeyCredential("account-master-key/ResourceToken");
CosmosClient cosmosClient = new CosmosClient(
            "account-endpoint-from-portal", 
            keyCredential, 
            new CosmosClientOptions()
            {
                ApplicationRegion = Regions.EastUS2,
            });

....

// To udpate key/credentials 
keyCredential.Update("updated master-key/ResourceToken");

// Dispose cosmosClient at application exit

Remarks

AzureKeyCredential enables changing/updating master-key/ResourceToken whle CosmosClient is still in use. The returned reference doesn't guarantee credentials or connectivity validations because creation doesn't make any network calls.

See Also

CosmosClient(string, TokenCredential, CosmosClientOptions)

Creates a new CosmosClient with the account endpoint URI string and TokenCredential.

CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. Please refer to the performance guide.

public CosmosClient(string accountEndpoint, TokenCredential tokenCredential, CosmosClientOptions clientOptions = null)

Parameters

accountEndpoint string

The cosmos service endpoint to use.

tokenCredential TokenCredential

Azure.Core.TokenCredentialThe token to provide AAD token for authorization.

clientOptions CosmosClientOptions

(Optional) client options

Remarks

The returned reference doesn't guarantee credentials or connectivity validations because creation doesn't make any network calls.

See Also

CosmosClient(string, CosmosClientOptions)

Creates a new CosmosClient with the connection string.

CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. Please refer to the performance guide.

public CosmosClient(string connectionString, CosmosClientOptions clientOptions = null)

Parameters

connectionString string

The connection string to the cosmos account. ex: AccountEndpoint=https://XXXXX.documents.azure.com:443/;AccountKey=SuperSecretKey;

clientOptions CosmosClientOptions

(Optional) client options

Examples

The CosmosClient is created with the connection string and configured to use "East US 2" region.

using Microsoft.Azure.Cosmos;

CosmosClient cosmosClient = new CosmosClient(
            "account-endpoint-from-portal", 
            "account-key-from-portal", 
            new CosmosClientOptions()
            {
                ApplicationRegion = Regions.EastUS2,
            });

// Dispose cosmosClient at application exit

Remarks

Emulator: To ignore SSL Certificate please suffix connectionstring with "DisableServerCertificateValidation=True;". When CosmosClientOptions.HttpClientFactory is used, SSL certificate needs to be handled appropriately. NOTE: DO NOT use this flag in production (only for emulator)

See Also

CosmosClient(string, string, CosmosClientOptions)

Creates a new CosmosClient with the account endpoint URI string and account key.

CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. Please refer to the performance guide.

public CosmosClient(string accountEndpoint, string authKeyOrResourceToken, CosmosClientOptions clientOptions = null)

Parameters

accountEndpoint string

The cosmos service endpoint to use

authKeyOrResourceToken string

The cosmos account key or resource token to use to create the client.

clientOptions CosmosClientOptions

(Optional) client options

Examples

The CosmosClient is created with the AccountEndpoint, AccountKey or ResourceToken and configured to use "East US 2" region.

using Microsoft.Azure.Cosmos;

CosmosClient cosmosClient = new CosmosClient(
            "account-endpoint-from-portal", 
            "account-key-from-portal", 
            new CosmosClientOptions()
            {
                ApplicationRegion = Regions.EastUS2,
            });

// Dispose cosmosClient at application exit

Remarks

The returned reference doesn't guarantee credentials or connectivity validations because creation doesn't make any network calls.

See Also

Properties

ClientOptions

The CosmosClientOptions used initialize CosmosClient.

public virtual CosmosClientOptions ClientOptions { get; }

Property Value

CosmosClientOptions

Remarks

This property is read-only. Modifying any options after the client has been created has no effect on the existing client instance.

See Also

Endpoint

Gets the endpoint Uri for the Azure Cosmos DB service.

public virtual Uri Endpoint { get; }

Property Value

Uri

The Uri for the account endpoint.

See Also
Uri

ResponseFactory

The response factory used to create CosmosClient response types.

public virtual CosmosResponseFactory ResponseFactory { get; }

Property Value

CosmosResponseFactory

Remarks

This can be used for generating responses for tests, and allows users to create a custom container that modifies the response. For example the client encryption uses this to decrypt responses before returning to the caller.

See Also

Methods

CreateAndInitializeAsync(string, AzureKeyCredential, IReadOnlyList<(string databaseId, string containerId)>, CosmosClientOptions, CancellationToken)

Creates a new CosmosClient with the account endpoint URI string and AzureKeyCredential. AzureKeyCredential enables changing/updating master-key/ResourceToken while CosmosClient is still in use.

In addition to that it initializes the client with containers provided i.e The SDK warms up the caches and connections before the first call to the service is made. Use this to obtain lower latency while startup of your application. CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. Please refer to the performance guide.

public static Task<CosmosClient> CreateAndInitializeAsync(string accountEndpoint, AzureKeyCredential authKeyOrResourceTokenCredential, IReadOnlyList<(string databaseId, string containerId)> containers, CosmosClientOptions cosmosClientOptions = null, CancellationToken cancellationToken = default)

Parameters

accountEndpoint string

The cosmos service endpoint to use

authKeyOrResourceTokenCredential AzureKeyCredential

AzureKeyCredential with master-key or resource token.

containers IReadOnlyList<(string databaseId, string containerId)>

Containers to be initialized identified by it's database name and container name.

cosmosClientOptions CosmosClientOptions

(Optional) client options

cancellationToken CancellationToken

(Optional) Cancellation Token

Returns

Task<CosmosClient>

A CosmosClient object.

Examples

The CosmosClient is created with the AccountEndpoint, AccountKey or ResourceToken and 2 containers in the account are initialized

using Microsoft.Azure.Cosmos;
List<(string, string)> containersToInitialize = new List<(string, string)>
{ ("DatabaseName1", "ContainerName1"), ("DatabaseName2", "ContainerName2") };

AzureKeyCredential keyCredential = new AzureKeyCredential("account-master-key/ResourceToken");
CosmosClient cosmosClient = await CosmosClient.CreateAndInitializeAsync("account-endpoint-from-portal", 
                                                                        keyCredential,
                                                                        containersToInitialize)

....

// To udpate key/credentials 
keyCredential.Update("updated master-key/ResourceToken");

// Dispose cosmosClient at application exit

Remarks

AzureKeyCredential enables changing/updating master-key/ResourceToken whle CosmosClient is still in use.

See Also

CreateAndInitializeAsync(string, TokenCredential, IReadOnlyList<(string databaseId, string containerId)>, CosmosClientOptions, CancellationToken)

Creates a new CosmosClient with the account endpoint URI string and TokenCredential. In addition to that it initializes the client with containers provided i.e The SDK warms up the caches and connections before the first call to the service is made. Use this to obtain lower latency while startup of your application. CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. Please refer to the performance guide.

public static Task<CosmosClient> CreateAndInitializeAsync(string accountEndpoint, TokenCredential tokenCredential, IReadOnlyList<(string databaseId, string containerId)> containers, CosmosClientOptions cosmosClientOptions = null, CancellationToken cancellationToken = default)

Parameters

accountEndpoint string

The cosmos service endpoint to use.

tokenCredential TokenCredential

Azure.Core.TokenCredentialThe token to provide AAD token for authorization.

containers IReadOnlyList<(string databaseId, string containerId)>

Containers to be initialized identified by it's database name and container name.

cosmosClientOptions CosmosClientOptions

(Optional) client options

cancellationToken CancellationToken

(Optional) Cancellation Token

Returns

Task<CosmosClient>

A CosmosClient object.

See Also

CreateAndInitializeAsync(string, IReadOnlyList<(string databaseId, string containerId)>, CosmosClientOptions, CancellationToken)

Creates a new CosmosClient with the account endpoint URI string and TokenCredential. In addition to that it initializes the client with containers provided i.e The SDK warms up the caches and connections before the first call to the service is made. Use this to obtain lower latency while startup of your application. CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. Please refer to the performance guide.

public static Task<CosmosClient> CreateAndInitializeAsync(string connectionString, IReadOnlyList<(string databaseId, string containerId)> containers, CosmosClientOptions cosmosClientOptions = null, CancellationToken cancellationToken = default)

Parameters

connectionString string

The connection string to the cosmos account. ex: AccountEndpoint=https://XXXXX.documents.azure.com:443/;AccountKey=SuperSecretKey;

containers IReadOnlyList<(string databaseId, string containerId)>

Containers to be initialized identified by it's database name and container name.

cosmosClientOptions CosmosClientOptions

(Optional) client options

cancellationToken CancellationToken

(Optional) Cancellation Token

Returns

Task<CosmosClient>

A CosmosClient object.

Examples

The CosmosClient is created with the ConnectionString and 2 containers in the account are initialized

using Microsoft.Azure.Cosmos;
List<(string, string)> containersToInitialize = new List<(string, string)>
{ ("DatabaseName1", "ContainerName1"), ("DatabaseName2", "ContainerName2") };

CosmosClient cosmosClient = await CosmosClient.CreateAndInitializeAsync("connection-string-from-portal",
                                                                        containersToInitialize)

// Dispose cosmosClient at application exit

Remarks

Emulator: To ignore SSL Certificate please suffix connectionstring with "DisableServerCertificateValidation=True;". When CosmosClientOptions.HttpClientFactory is used, SSL certificate needs to be handled appropriately. NOTE: DO NOT use this flag in production (only for emulator)

See Also

CreateAndInitializeAsync(string, string, IReadOnlyList<(string databaseId, string containerId)>, CosmosClientOptions, CancellationToken)

Creates a new CosmosClient with the account endpoint URI string and TokenCredential. In addition to that it initializes the client with containers provided i.e The SDK warms up the caches and connections before the first call to the service is made. Use this to obtain lower latency while startup of your application. CosmosClient is thread-safe. Its recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance. Please refer to the performance guide.

public static Task<CosmosClient> CreateAndInitializeAsync(string accountEndpoint, string authKeyOrResourceToken, IReadOnlyList<(string databaseId, string containerId)> containers, CosmosClientOptions cosmosClientOptions = null, CancellationToken cancellationToken = default)

Parameters

accountEndpoint string

The cosmos service endpoint to use

authKeyOrResourceToken string

The cosmos account key or resource token to use to create the client.

containers IReadOnlyList<(string databaseId, string containerId)>

Containers to be initialized identified by it's database name and container name.

cosmosClientOptions CosmosClientOptions

(Optional) client options

cancellationToken CancellationToken

(Optional) Cancellation Token

Returns

Task<CosmosClient>

A CosmosClient object.

Examples

The CosmosClient is created with the AccountEndpoint, AccountKey or ResourceToken and 2 containers in the account are initialized

using Microsoft.Azure.Cosmos;
List<(string, string)> containersToInitialize = new List<(string, string)>
{ ("DatabaseName1", "ContainerName1"), ("DatabaseName2", "ContainerName2") };

CosmosClient cosmosClient = await CosmosClient.CreateAndInitializeAsync("account-endpoint-from-portal", 
                                                                        "account-key-from-portal",
                                                                        containersToInitialize)

// Dispose cosmosClient at application exit

Remarks

The returned reference doesn't guarantee credentials or connectivity validations because initialization doesn't make any network calls.

See Also

CreateDatabaseAsync(string, ThroughputProperties, RequestOptions, CancellationToken)

Sends a request for creating a database.

A database manages users, permissions and a set of containers. Each Azure Cosmos DB Database Account is able to support multiple independent named databases, with the database being the logical container for data.

Each Database consists of one or more containers, each of which in turn contain one or more documents. Since databases are an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs.

public virtual Task<DatabaseResponse> CreateDatabaseAsync(string id, ThroughputProperties throughputProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The database id.

throughputProperties ThroughputProperties

(Optional) The throughput provisioned for a database in measurement of Request Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) A set of options that can be set.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<DatabaseResponse>

A Task containing a DatabaseResponse which wraps a DatabaseProperties containing the resource record.

See Also

CreateDatabaseAsync(string, int?, RequestOptions, CancellationToken)

Sends a request for creating a database.

A database manages users, permissions and a set of containers. Each Azure Cosmos DB Database Account is able to support multiple independent named databases, with the database being the logical container for data.

Each Database consists of one or more containers, each of which in turn contain one or more documents. Since databases are an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs.

public virtual Task<DatabaseResponse> CreateDatabaseAsync(string id, int? throughput = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The database id.

throughput int?

(Optional) The throughput provisioned for a database in measurement of Request Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) A set of options that can be set.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<DatabaseResponse>

A Task containing a DatabaseResponse which wraps a DatabaseProperties containing the resource record.

See Also

CreateDatabaseIfNotExistsAsync(string, ThroughputProperties, RequestOptions, CancellationToken)

Check if a database exists, and if it doesn't, create it. Only the database id is used to verify if there is an existing database. Other database properties such as throughput are not validated and can be different then the passed properties.

A database manages users, permissions and a set of containers. Each Azure Cosmos DB Database Account is able to support multiple independent named databases, with the database being the logical container for data.

Each Database consists of one or more containers, each of which in turn contain one or more documents. Since databases are an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs.

public virtual Task<DatabaseResponse> CreateDatabaseIfNotExistsAsync(string id, ThroughputProperties throughputProperties, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The database id.

throughputProperties ThroughputProperties

The throughput provisioned for a database in measurement of Request Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) A set of additional options that can be set.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<DatabaseResponse>

A Task containing a DatabaseResponse which wraps a DatabaseProperties containing the resource record.

StatusCodeCommon success StatusCodes for the CreateDatabaseIfNotExistsAsync operation
201Created - New database is created.
200OK - This means the database already exists.
See Also

CreateDatabaseIfNotExistsAsync(string, int?, RequestOptions, CancellationToken)

Check if a database exists, and if it doesn't, create it. Only the database id is used to verify if there is an existing database. Other database properties such as throughput are not validated and can be different then the passed properties.

A database manages users, permissions and a set of containers. Each Azure Cosmos DB Database Account is able to support multiple independent named databases, with the database being the logical container for data.

Each Database consists of one or more containers, each of which in turn contain one or more documents. Since databases are an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs.

public virtual Task<DatabaseResponse> CreateDatabaseIfNotExistsAsync(string id, int? throughput = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

id string

The database id.

throughput int?

(Optional) The throughput provisioned for a database in measurement of Request Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) A set of additional options that can be set.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<DatabaseResponse>

A Task containing a DatabaseResponse which wraps a DatabaseProperties containing the resource record.

StatusCodeCommon success StatusCodes for the CreateDatabaseIfNotExistsAsync operation
201Created - New database is created.
200OK- This means the database already exists.
See Also

CreateDatabaseStreamAsync(DatabaseProperties, int?, RequestOptions, CancellationToken)

Send a request for creating a database.

A database manages users, permissions and a set of containers. Each Azure Cosmos DB Database Account is able to support multiple independent named databases, with the database being the logical container for data.

Each Database consists of one or more containers, each of which in turn contain one or more documents. Since databases are an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs.

public virtual Task<ResponseMessage> CreateDatabaseStreamAsync(DatabaseProperties databaseProperties, int? throughput = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)

Parameters

databaseProperties DatabaseProperties

The database properties

throughput int?

(Optional) The throughput provisioned for a database in measurement of Request Units per second in the Azure Cosmos DB service.

requestOptions RequestOptions

(Optional) A set of options that can be set.

cancellationToken CancellationToken

(Optional) CancellationToken representing request cancellation.

Returns

Task<ResponseMessage>

A Task containing a DatabaseResponse which wraps a DatabaseProperties containing the resource record.

See Also

Dispose()

Dispose of cosmos client

public void Dispose()
See Also

Dispose(bool)

Dispose of cosmos client

protected virtual void Dispose(bool disposing)

Parameters

disposing bool

True if disposing

See Also

GetContainer(string, string)

Returns a proxy reference to a container.

public virtual Container GetContainer(string databaseId, string containerId)

Parameters

databaseId string

Cosmos database name

containerId string

Cosmos container name

Returns

Container

Cosmos container proxy

Remarks

See Also

GetDatabase(string)

Returns a proxy reference to a database.

public virtual Database GetDatabase(string id)

Parameters

id string

The Cosmos database id

Returns

Database

Cosmos database proxy

Examples

Database db = cosmosClient.GetDatabase("myDatabaseId");
DatabaseResponse response = await db.ReadAsync();

Remarks

Database proxy reference doesn't guarantee existence. Please ensure database exists through CreateDatabaseAsync(string, int?, RequestOptions, CancellationToken) or CreateDatabaseIfNotExistsAsync(string, int?, RequestOptions, CancellationToken), before operating on it.

See Also

GetDatabaseQueryIterator<T>(QueryDefinition, string, QueryRequestOptions)

This method creates a query for databases under an Cosmos DB Account using a SQL statement with parameterized values. It returns a FeedIterator. For more information on preparing SQL statements with parameterized values, please see QueryDefinition.

public virtual FeedIterator<T> GetDatabaseQueryIterator<T>(QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryDefinition QueryDefinition

The cosmos SQL query definition.

continuationToken string

The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

Returns

FeedIterator<T>

An iterator to go through the databases.

Type Parameters

T

Examples

This create the type feed iterator for database with queryText as input,

QueryDefinition queryDefinition = new QueryDefinition("SELECT * FROM c where c.status like @status")
    .WithParameter("@status", "start%");
using (FeedIterator<DatabaseProperties> feedIterator = this.users.GetDatabaseQueryIterator<DatabaseProperties>(queryDefinition))
{
    while (feedIterator.HasMoreResults)
    {
        FeedResponse<DatabaseProperties> response = await feedIterator.ReadNextAsync();
        foreach (var database in response)
        {
            Console.WriteLine(database);
        }
    }
}

Remarks

Refer to https://docs.microsoft.com/azure/cosmos-db/sql-query-getting-started for syntax and examples.

ReadAsync(RequestOptions, CancellationToken) is recommended for single database look-up.

See Also

GetDatabaseQueryIterator<T>(string, string, QueryRequestOptions)

This method creates a query for databases under an Cosmos DB Account using a SQL statement. It returns a FeedIterator.

public virtual FeedIterator<T> GetDatabaseQueryIterator<T>(string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryText string

The cosmos SQL query text.

continuationToken string

The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the item query request.

Returns

FeedIterator<T>

An iterator to go through the databases.

Type Parameters

T

Examples

This create the type feed iterator for database with queryText as input,

string queryText = "SELECT * FROM c where c.status like 'start%'";
using (FeedIterator<DatabaseProperties> feedIterator = this.users.GetDatabaseQueryIterator<DatabaseProperties>(queryText)
{
    while (feedIterator.HasMoreResults)
    {
        FeedResponse<DatabaseProperties> response = await feedIterator.ReadNextAsync();
        foreach (var database in response)
        {
            Console.WriteLine(database);
        }
    }
}

Remarks

Refer to https://docs.microsoft.com/azure/cosmos-db/sql-query-getting-started for syntax and examples.

ReadAsync(RequestOptions, CancellationToken) is recommended for single database look-up.

See Also

GetDatabaseQueryStreamIterator(QueryDefinition, string, QueryRequestOptions)

This method creates a query for databases under an Cosmos DB Account using a SQL statement with parameterized values. It returns a FeedIterator. For more information on preparing SQL statements with parameterized values, please see QueryDefinition.

public virtual FeedIterator GetDatabaseQueryStreamIterator(QueryDefinition queryDefinition, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryDefinition QueryDefinition

The cosmos SQL query definition.

continuationToken string

The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the query request.

Returns

FeedIterator

An iterator to go through the databases

Examples

Example on how to fully drain the query results.

QueryDefinition queryDefinition = new QueryDefinition("select * From c where c._rid = @rid")
              .WithParameter("@rid", "TheRidValue");
using (FeedIterator feedIterator = this.CosmosClient.GetDatabaseQueryStreamIterator(
    queryDefinition)
{
    while (feedIterator.HasMoreResults)
    {
        // Stream iterator returns a response with status for errors
        using(ResponseMessage response = await feedIterator.ReadNextAsync())
        {
            // Handle failure scenario. 
            if(!response.IsSuccessStatusCode)
            {
                // Log the response.Diagnostics and handle the error
            }
        }
    }
}

Remarks

Refer to https://docs.microsoft.com/azure/cosmos-db/sql-query-getting-started for syntax and examples.

ReadStreamAsync(RequestOptions, CancellationToken) is recommended for single database look-up.

See Also

GetDatabaseQueryStreamIterator(string, string, QueryRequestOptions)

This method creates a query for databases under an Cosmos DB Account using a SQL statement. It returns a FeedIterator.

public virtual FeedIterator GetDatabaseQueryStreamIterator(string queryText = null, string continuationToken = null, QueryRequestOptions requestOptions = null)

Parameters

queryText string

The cosmos SQL query text.

continuationToken string

The continuation token in the Azure Cosmos DB service.

requestOptions QueryRequestOptions

(Optional) The options for the query request.

Returns

FeedIterator

An iterator to go through the databases

Examples

Example on how to fully drain the query results.

using (FeedIterator feedIterator = this.CosmosClient.GetDatabaseQueryStreamIterator(
    ("select * From c where c._rid = 'TheRidValue'")
{
    while (feedIterator.HasMoreResults)
    {
        // Stream iterator returns a response with status for errors
        using(ResponseMessage response = await feedIterator.ReadNextAsync())
        {
            // Handle failure scenario. 
            if(!response.IsSuccessStatusCode)
            {
                // Log the response.Diagnostics and handle the error
            }
        }
    }
}

Remarks

Refer to https://docs.microsoft.com/azure/cosmos-db/sql-query-getting-started for syntax and examples.

ReadStreamAsync(RequestOptions, CancellationToken) is recommended for single database look-up.

See Also

ReadAccountAsync()

Reads the AccountProperties for the Azure Cosmos DB account.

public virtual Task<AccountProperties> ReadAccountAsync()

Returns

Task<AccountProperties>

A AccountProperties wrapped in a Task object.

See Also

See Also