Documentation ¶
Overview ¶
Package azcosmos implements the client to interact with the Azure Cosmos DB SQL API.
The azcosmos package is capable of:
- Creating, deleting, and reading databases in an account
- Creating, deleting, updating, and reading containers in a database
- Creating, deleting, replacing, upserting, and reading items in a container
Creating the Client ¶
To create a client, you will need the account's endpoint URL and a key credential.
cred, err := azcosmos.NewKeyCredential("myAccountKey") handle(err) client, err := azcosmos.NewClientWithKey("myAccountEndpointURL", cred, nil) handle(err)
Key Concepts ¶
The following are relevant concepts for the usage of the client:
- A client is a connection to an Azure Cosmos DB account.
- An account can have multiple databases, and the client allows you to create, read, and delete databases.
- A database can have multiple containers, and the client allows you to create, read, update, and delete containers, and to modify throughput provision.
- Information is stored as items inside containers and the client allows you to create, read, update, and delete items in containers.
More Examples ¶
The following sections provide several code snippets covering some of the most common Table tasks, including:
- Creating a database
- Creating a container
- Creating, reading, and deleting items
Creating a database ¶
Create a database and obtain a `DatabaseClient` to perform operations on your newly created database.
cred, err := azcosmos.NewKeyCredential("myAccountKey") handle(err) client, err := azcosmos.NewClientWithKey("myAccountEndpointURL", cred, nil) handle(err) database := azcosmos.DatabaseProperties{ID: "myDatabase"} response, err := client.CreateDatabase(context, database, nil) handle(err) database, err := azcosmos.NewDatabase("myDatabase") handle(err)
Creating a container ¶
Create a container on an existing database and obtain a `ContainerClient` to perform operations on your newly created container.
cred, err := azcosmos.NewKeyCredential("myAccountKey") handle(err) client, err := azcosmos.NewClientWithKey("myAccountEndpointURL", cred, nil) handle(err) database := azcosmos.NewDatabase("myDatabase") properties := azcosmos.ContainerProperties{ ID: "myContainer", PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{ Paths: []string{"/myPartitionKeyProperty"}, }, } throughput := azcosmos.NewManualThroughputProperties(400) response, err := database.CreateContainer(context, properties, &CreateContainerOptions{ThroughputProperties: &throughput}) handle(err) container, err := database.NewContainer("myContainer") handle(err)
Creating, reading, and deleting items
item := map[string]string{ "id": "1", "myPartitionKeyProperty": "myPartitionKeyValue", "otherValue": 10 } marshalled, err := json.Marshal(item) handle(err) pk := azcosmos.NewPartitionKeyString("myPartitionKeyValue") itemResponse, err := container.CreateItem(context, pk, marshalled, nil) handle(err) id := "1" itemResponse, err = container.ReadItem(context, pk, id, nil) handle(err) var itemResponseBody map[string]string err = json.Unmarshal(itemResponse.Value, &itemResponseBody) handle(err) itemResponseBody["value"] = "3" marshalledReplace, err := json.Marshal(itemResponseBody) handle(err) itemResponse, err = container.ReplaceItem(context, pk, id, marshalledReplace, nil) handle(err) itemResponse, err = container.DeleteItem(context, pk, id, nil) handle(err)
Index ¶
- type Client
- func (c *Client) CreateDatabase(ctx context.Context, databaseProperties DatabaseProperties, ...) (DatabaseResponse, error)
- func (c *Client) Endpoint() string
- func (c *Client) NewContainer(databaseId string, containerId string) (*ContainerClient, error)
- func (c *Client) NewDatabase(id string) (*DatabaseClient, error)
- type ClientOptions
- type CompositeIndex
- type CompositeIndexOrder
- type ConflictResolutionMode
- type ConflictResolutionPolicy
- type ConsistencyLevel
- type ContainerClient
- func (c *ContainerClient) CreateItem(ctx context.Context, partitionKey PartitionKey, item []byte, o *ItemOptions) (ItemResponse, error)
- func (c *ContainerClient) Delete(ctx context.Context, o *DeleteContainerOptions) (ContainerResponse, error)
- func (c *ContainerClient) DeleteItem(ctx context.Context, partitionKey PartitionKey, itemId string, o *ItemOptions) (ItemResponse, error)
- func (c *ContainerClient) ID() string
- func (c *ContainerClient) Read(ctx context.Context, o *ReadContainerOptions) (ContainerResponse, error)
- func (c *ContainerClient) ReadItem(ctx context.Context, partitionKey PartitionKey, itemId string, o *ItemOptions) (ItemResponse, error)
- func (c *ContainerClient) ReadThroughput(ctx context.Context, o *ThroughputOptions) (ThroughputResponse, error)
- func (c *ContainerClient) Replace(ctx context.Context, containerProperties ContainerProperties, ...) (ContainerResponse, error)
- func (c *ContainerClient) ReplaceItem(ctx context.Context, partitionKey PartitionKey, itemId string, item []byte, ...) (ItemResponse, error)
- func (c *ContainerClient) ReplaceThroughput(ctx context.Context, throughputProperties ThroughputProperties, ...) (ThroughputResponse, error)
- func (c *ContainerClient) UpsertItem(ctx context.Context, partitionKey PartitionKey, item []byte, o *ItemOptions) (ItemResponse, error)
- type ContainerProperties
- type ContainerResponse
- type CreateContainerOptions
- type CreateDatabaseOptions
- type DataType
- type DatabaseClient
- func (db *DatabaseClient) CreateContainer(ctx context.Context, containerProperties ContainerProperties, ...) (ContainerResponse, error)
- func (db *DatabaseClient) Delete(ctx context.Context, o *DeleteDatabaseOptions) (DatabaseResponse, error)
- func (db *DatabaseClient) ID() string
- func (db *DatabaseClient) NewContainer(id string) (*ContainerClient, error)
- func (db *DatabaseClient) Read(ctx context.Context, o *ReadDatabaseOptions) (DatabaseResponse, error)
- func (db *DatabaseClient) ReadThroughput(ctx context.Context, o *ThroughputOptions) (ThroughputResponse, error)
- func (db *DatabaseClient) ReplaceThroughput(ctx context.Context, throughputProperties ThroughputProperties, ...) (ThroughputResponse, error)
- type DatabaseProperties
- type DatabaseResponse
- type DeleteContainerOptions
- type DeleteDatabaseOptions
- type ExcludedPath
- type IncludedPath
- type IndexingDirective
- type IndexingMode
- type IndexingPolicy
- type ItemOptions
- type ItemResponse
- type KeyCredential
- type PartitionKey
- type PartitionKeyDefinition
- type ReadContainerOptions
- type ReadDatabaseOptions
- type ReplaceContainerOptions
- type Response
- type SpatialIndex
- type SpatialType
- type ThroughputOptions
- type ThroughputProperties
- func (tp *ThroughputProperties) AutoscaleIncrement() (int32, bool)
- func (tp *ThroughputProperties) AutoscaleMaxThroughput() (int32, bool)
- func (tp *ThroughputProperties) ManualThroughput() (int32, bool)
- func (tp *ThroughputProperties) MarshalJSON() ([]byte, error)
- func (tp *ThroughputProperties) UnmarshalJSON(b []byte) error
- type ThroughputResponse
- type UniqueKey
- type UniqueKeyPolicy
Examples ¶
- Client.CreateDatabase
- ContainerClient.CreateItem
- ContainerClient.DeleteItem
- ContainerClient.ReadItem
- ContainerClient.ReadItem (SessionConsistency)
- ContainerClient.Replace
- ContainerClient.ReplaceItem
- ContainerClient.ReplaceItem (OptimisticConcurrency)
- ContainerClient.ReplaceThroughput
- DatabaseClient.CreateContainer
- NewClientWithKey
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Cosmos client is used to interact with the Azure Cosmos DB database service.
func NewClientWithKey ¶
func NewClientWithKey(endpoint string, cred KeyCredential, o *ClientOptions) (*Client, error)
NewClientWithKey creates a new instance of Cosmos client with the specified values. It uses the default pipeline configuration. endpoint - The cosmos service endpoint to use. cred - The credential used to authenticate with the cosmos service. options - Optional Cosmos client options. Pass nil to accept default values.
Example ¶
package main import ( "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } // Create new Cosmos DB client. cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } fmt.Println(client) }
Output:
func (*Client) CreateDatabase ¶
func (c *Client) CreateDatabase( ctx context.Context, databaseProperties DatabaseProperties, o *CreateDatabaseOptions) (DatabaseResponse, error)
CreateDatabase creates a new database. ctx - The context for the request. databaseProperties - The definition of the database o - Options for the create database operation.
Example ¶
package main import ( "context" "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } databaseProperties := azcosmos.DatabaseProperties{ID: "databaseName"} databaseResponse, err := client.CreateDatabase(context.Background(), databaseProperties, nil) if err != nil { panic(err) } fmt.Printf("Database created. ActivityId %s", databaseResponse.ActivityID) }
Output:
func (*Client) NewContainer ¶
func (c *Client) NewContainer(databaseId string, containerId string) (*ContainerClient, error)
NewContainer returns a struct that represents a container and allows container level operations. databaseId - The id of the database. containerId - The id of the container.
func (*Client) NewDatabase ¶
func (c *Client) NewDatabase(id string) (*DatabaseClient, error)
NewDatabase returns a struct that represents a database and allows database level operations. id - The id of the database.
type ClientOptions ¶
type ClientOptions struct { azcore.ClientOptions // When EnableContentResponseOnWrite is false will cause the response to have a null resource. This reduces networking and CPU load by not sending the resource back over the network and serializing it on the client. // The default is false. EnableContentResponseOnWrite bool }
ClientOptions defines the options for the Cosmos client.
type CompositeIndex ¶
type CompositeIndex struct { // Path for the index. Path string `json:"path"` // Order represents the order of the composite index. // For example if you want to run the query "SELECT * FROM c ORDER BY c.age asc, c.height desc", // then you need to make the order for "/age" "ascending" and the order for "/height" "descending". Order CompositeIndexOrder `json:"order"` }
type CompositeIndexOrder ¶
type CompositeIndexOrder string
These are the ordering values available for composite indexes in the Azure Cosmos DB database service. For more information see https://docs.microsoft.com/azure/cosmos-db/index-policy
const ( // Ascending sort order for composite paths. CompositeIndexAscending CompositeIndexOrder = "ascending" // Descending sort order for composite paths. CompositeIndexDescending CompositeIndexOrder = "descending" )
func CompositeIndexOrderValues ¶
func CompositeIndexOrderValues() []CompositeIndexOrder
Returns a list of available consistency levels
func (CompositeIndexOrder) ToPtr ¶
func (c CompositeIndexOrder) ToPtr() *CompositeIndexOrder
type ConflictResolutionMode ¶
type ConflictResolutionMode string
ConflictResolutionMode defines the conflict resolution mode in the Azure Cosmos DB service.
const ( // Conflict resolution that uses the highest value of the conflicting documents property values. ConflictResolutionModeLastWriteWins ConflictResolutionMode = "LastWriterWins" // Custom conflict resolution mode that requires the definition of a stored procedure. ConflictResolutionModeCustom ConflictResolutionMode = "Custom" )
func ConflictResolutionModeValues ¶
func ConflictResolutionModeValues() []ConflictResolutionMode
Returns a list of available consistency levels
func (ConflictResolutionMode) ToPtr ¶
func (c ConflictResolutionMode) ToPtr() *ConflictResolutionMode
type ConflictResolutionPolicy ¶
type ConflictResolutionPolicy struct { // Conflict resolution mode. By default, the conflict resolution mode is LastWriteWins. Mode ConflictResolutionMode `json:"mode"` // The path which is present in each item in the container to be used on LastWriteWins conflict resolution. // It must be an integer value. ResolutionPath string `json:"conflictResolutionPath,omitempty"` // The stored procedure path on Custom conflict. // The path should be the full path to the procedure ResolutionProcedure string `json:"conflictResolutionProcedure,omitempty"` }
ConflictResolutionPolicy represents a conflict resolution policy for a container. For more information see https://docs.microsoft.com/azure/cosmos-db/unique-keys
type ConsistencyLevel ¶
type ConsistencyLevel string
Consistency levels supported by the Azure Cosmos DB service.
const ( ConsistencyLevelStrong ConsistencyLevel = "Strong" ConsistencyLevelBoundedStaleness ConsistencyLevel = "BoundedStaleness" ConsistencyLevelSession ConsistencyLevel = "Session" ConsistencyLevelEventual ConsistencyLevel = "Eventual" ConsistencyLevelConsistentPrefix ConsistencyLevel = "ConsistentPrefix" )
func ConsistencyLevelValues ¶
func ConsistencyLevelValues() []ConsistencyLevel
Returns a list of available consistency levels
func (ConsistencyLevel) ToPtr ¶
func (c ConsistencyLevel) ToPtr() *ConsistencyLevel
type ContainerClient ¶
type ContainerClient struct {
// contains filtered or unexported fields
}
A ContainerClient lets you perform read, update, change throughput, and delete container operations. It also lets you perform read, update, change throughput, and delete item operations.
func (*ContainerClient) CreateItem ¶
func (c *ContainerClient) CreateItem( ctx context.Context, partitionKey PartitionKey, item []byte, o *ItemOptions) (ItemResponse, error)
Creates an item in a Cosmos container. ctx - The context for the request. partitionKey - The partition key for the item. item - The item to create. o - Options for the operation.
Example ¶
package main import ( "context" "encoding/json" "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } container, err := client.NewContainer("databaseName", "aContainer") if err != nil { panic(err) } pk := azcosmos.NewPartitionKeyString("newPartitionKey") item := map[string]string{ "id": "anId", "value": "2", "myPartitionKey": "newPartitionKey", } marshalled, err := json.Marshal(item) if err != nil { panic(err) } itemResponse, err := container.CreateItem(context.Background(), pk, marshalled, nil) if err != nil { panic(err) } fmt.Printf("Item created. ActivityId %s consuming %v RU", itemResponse.ActivityID, itemResponse.RequestCharge) }
Output:
func (*ContainerClient) Delete ¶
func (c *ContainerClient) Delete( ctx context.Context, o *DeleteContainerOptions) (ContainerResponse, error)
Delete a Cosmos container. ctx - The context for the request. o - Options for the operation.
func (*ContainerClient) DeleteItem ¶
func (c *ContainerClient) DeleteItem( ctx context.Context, partitionKey PartitionKey, itemId string, o *ItemOptions) (ItemResponse, error)
Deletes an item in a Cosmos container. ctx - The context for the request. partitionKey - The partition key for the item. itemId - The id of the item to delete. o - Options for the operation.
Example ¶
package main import ( "context" "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } container, err := client.NewContainer("databaseName", "aContainer") if err != nil { panic(err) } pk := azcosmos.NewPartitionKeyString("newPartitionKey") id := "anId" itemResponse, err := container.DeleteItem(context.Background(), pk, id, nil) if err != nil { panic(err) } fmt.Printf("Item deleted. ActivityId %s consuming %v RU", itemResponse.ActivityID, itemResponse.RequestCharge) }
Output:
func (*ContainerClient) ID ¶
func (c *ContainerClient) ID() string
ID returns the identifier of the Cosmos container.
func (*ContainerClient) Read ¶
func (c *ContainerClient) Read( ctx context.Context, o *ReadContainerOptions) (ContainerResponse, error)
Read obtains the information for a Cosmos container. ctx - The context for the request. o - Options for the operation.
func (*ContainerClient) ReadItem ¶
func (c *ContainerClient) ReadItem( ctx context.Context, partitionKey PartitionKey, itemId string, o *ItemOptions) (ItemResponse, error)
Reads an item in a Cosmos container. ctx - The context for the request. partitionKey - The partition key for the item. itemId - The id of the item to read. o - Options for the operation.
Example ¶
package main import ( "context" "encoding/json" "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } container, err := client.NewContainer("databaseName", "aContainer") if err != nil { panic(err) } pk := azcosmos.NewPartitionKeyString("newPartitionKey") id := "anId" itemResponse, err := container.ReadItem(context.Background(), pk, id, nil) if err != nil { panic(err) } var itemResponseBody map[string]string err = json.Unmarshal(itemResponse.Value, &itemResponseBody) if err != nil { panic(err) } fmt.Printf("Item read. ActivityId %s consuming %v RU", itemResponse.ActivityID, itemResponse.RequestCharge) }
Output:
Example (SessionConsistency) ¶
package main import ( "context" "encoding/json" "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } container, err := client.NewContainer("databaseName", "aContainer") if err != nil { panic(err) } pk := azcosmos.NewPartitionKeyString("newPartitionKey") id := "anId" item := map[string]string{ "id": "anId", "value": "2", "myPartitionKey": "newPartitionKey", } marshalled, err := json.Marshal(item) if err != nil { panic(err) } itemResponse, err := container.CreateItem(context.Background(), pk, marshalled, nil) if err != nil { panic(err) } itemSessionToken := itemResponse.SessionToken fmt.Printf("Create response contained session %s", itemSessionToken) // In another client, maintain the session by passing the session token itemResponse, err = container.ReadItem(context.Background(), pk, id, &azcosmos.ItemOptions{SessionToken: itemSessionToken}) if err != nil { panic(err) } fmt.Printf("Item read. ActivityId %s consuming %v RU", itemResponse.ActivityID, itemResponse.RequestCharge) }
Output:
func (*ContainerClient) ReadThroughput ¶
func (c *ContainerClient) ReadThroughput( ctx context.Context, o *ThroughputOptions) (ThroughputResponse, error)
ReadThroughput obtains the provisioned throughput information for the container. ctx - The context for the request. o - Options for the operation.
func (*ContainerClient) Replace ¶
func (c *ContainerClient) Replace( ctx context.Context, containerProperties ContainerProperties, o *ReplaceContainerOptions) (ContainerResponse, error)
Replace a Cosmos container. ctx - The context for the request. o - Options for the operation.
Example ¶
package main import ( "context" "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } container, err := client.NewContainer("databaseName", "aContainer") if err != nil { panic(err) } containerResponse, err := container.Read(context.Background(), nil) if err != nil { panic(err) } // Changing the indexing policy containerResponse.ContainerProperties.IndexingPolicy = &azcosmos.IndexingPolicy{ IncludedPaths: []azcosmos.IncludedPath{}, ExcludedPaths: []azcosmos.ExcludedPath{}, Automatic: false, IndexingMode: azcosmos.IndexingModeNone, } // Replace container properties replaceResponse, err := container.Replace(context.Background(), *containerResponse.ContainerProperties, nil) if err != nil { panic(err) } fmt.Printf("Container updated. ActivityId %s", replaceResponse.ActivityID) }
Output:
func (*ContainerClient) ReplaceItem ¶
func (c *ContainerClient) ReplaceItem( ctx context.Context, partitionKey PartitionKey, itemId string, item []byte, o *ItemOptions) (ItemResponse, error)
Replaces an item in a Cosmos container. ctx - The context for the request. partitionKey - The partition key of the item to replace. itemId - The id of the item to replace. item - The content to be used to replace. o - Options for the operation.
Example ¶
package main import ( "context" "encoding/json" "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } container, err := client.NewContainer("databaseName", "aContainer") if err != nil { panic(err) } pk := azcosmos.NewPartitionKeyString("newPartitionKey") id := "anId" itemResponse, err := container.ReadItem(context.Background(), pk, id, nil) if err != nil { panic(err) } var itemResponseBody map[string]string err = json.Unmarshal(itemResponse.Value, &itemResponseBody) if err != nil { panic(err) } // Modify some property itemResponseBody["value"] = "newValue" marshalledReplace, err := json.Marshal(itemResponseBody) if err != nil { panic(err) } itemResponse, err = container.ReplaceItem(context.Background(), pk, id, marshalledReplace, nil) if err != nil { panic(err) } fmt.Printf("Item replaced. ActivityId %s consuming %v RU", itemResponse.ActivityID, itemResponse.RequestCharge) }
Output:
Example (OptimisticConcurrency) ¶
Azure Cosmos DB supports optimistic concurrency control to prevent lost updates or deletes and detection of conflicting operations. Check the item response status code. If an error is emitted and the response code is 412 then retry operation.
package main import ( "context" "encoding/json" "errors" "fmt" "os" "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } container, err := client.NewContainer("databaseName", "aContainer") if err != nil { panic(err) } pk := azcosmos.NewPartitionKeyString("newPartitionKey") id := "anId" numberRetry := 3 // Defining a limit on retries err = retryOptimisticConcurrency(numberRetry, 10*time.Millisecond, func() (bool, error) { itemResponse, err := container.ReadItem(context.Background(), pk, id, nil) if err != nil { panic(err) } var itemResponseBody map[string]string err = json.Unmarshal(itemResponse.Value, &itemResponseBody) if err != nil { panic(err) } // Change a value in the item response body. itemResponseBody["value"] = "newValue" marshalledReplace, err := json.Marshal(itemResponseBody) if err != nil { panic(err) } // Replace with Etag etag := itemResponse.ETag itemResponse, err = container.ReplaceItem(context.Background(), pk, id, marshalledReplace, &azcosmos.ItemOptions{IfMatchEtag: &etag}) var httpErr azcore.HTTPResponse return (errors.As(err, &httpErr) && itemResponse.RawResponse.StatusCode == 412), err }) if err != nil { panic(err) } } func retryOptimisticConcurrency(retryAttempts int, wait time.Duration, retry func() (bool, error)) (result error) { for i := 0; ; i++ { retryResult, err := retry() if err != nil { break } if !(retryResult) { break } if i >= (retryAttempts - 1) { break } fmt.Printf("retrying after error: %v", err) time.Sleep(wait) } return fmt.Errorf("Cosmos DB retry attempts %d, error: %s", retryAttempts, result) }
Output:
func (*ContainerClient) ReplaceThroughput ¶
func (c *ContainerClient) ReplaceThroughput( ctx context.Context, throughputProperties ThroughputProperties, o *ThroughputOptions) (ThroughputResponse, error)
ReplaceThroughput updates the provisioned throughput for the container. ctx - The context for the request. throughputProperties - The throughput configuration of the container. o - Options for the operation.
Example ¶
package main import ( "context" "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } container, err := client.NewContainer("databaseName", "aContainer") if err != nil { panic(err) } throughputResponse, err := container.ReadThroughput(context.Background(), nil) if err != nil { panic(err) } manualThroughput, hasManual := throughputResponse.ThroughputProperties.ManualThroughput() if !hasManual { panic("Expected to have manual throughput") } fmt.Printf("Container is provisioned with %v RU/s", manualThroughput) // Replace manual throughput newScale := azcosmos.NewManualThroughputProperties(500) replaceThroughputResponse, err := container.ReplaceThroughput(context.Background(), newScale, nil) if err != nil { panic(err) } fmt.Printf("Throughput updated. ActivityId %s", replaceThroughputResponse.ActivityID) }
Output:
func (*ContainerClient) UpsertItem ¶
func (c *ContainerClient) UpsertItem( ctx context.Context, partitionKey PartitionKey, item []byte, o *ItemOptions) (ItemResponse, error)
Upserts (create or replace) an item in a Cosmos container. ctx - The context for the request. partitionKey - The partition key for the item. item - The item to upsert. o - Options for the operation.
type ContainerProperties ¶
type ContainerProperties struct { // ID contains the unique id of the container. ID string // ETag contains the entity etag of the container. ETag *azcore.ETag // SelfLink contains the self-link of the container. SelfLink string // ResourceID contains the resource id of the container. ResourceID string // LastModified contains the last modified time of the container. LastModified time.Time // DefaultTimeToLive contains the default time to live in seconds for items in the container. // For more information see https://docs.microsoft.com/azure/cosmos-db/time-to-live#time-to-live-configurations DefaultTimeToLive *int32 // AnalyticalStoreTimeToLiveInSeconds contains the default time to live in seconds for analytical store in the container. // For more information see https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction#analytical-ttl AnalyticalStoreTimeToLiveInSeconds *int32 // PartitionKeyDefinition contains the partition key definition of the container. PartitionKeyDefinition PartitionKeyDefinition // IndexingPolicy contains the indexing definition of the container. IndexingPolicy *IndexingPolicy // UniqueKeyPolicy contains the unique key policy of the container. UniqueKeyPolicy *UniqueKeyPolicy // ConflictResolutionPolicy contains the conflict resolution policy of the container. ConflictResolutionPolicy *ConflictResolutionPolicy }
ContainerProperties represents the properties of a container.
func (ContainerProperties) MarshalJSON ¶
func (tp ContainerProperties) MarshalJSON() ([]byte, error)
func (*ContainerProperties) UnmarshalJSON ¶
func (tp *ContainerProperties) UnmarshalJSON(b []byte) error
type ContainerResponse ¶
type ContainerResponse struct { // ContainerProperties contains the unmarshalled response body in ContainerProperties format. ContainerProperties *ContainerProperties Response }
ContainerResponse represents the response from a container request.
type CreateContainerOptions ¶
type CreateContainerOptions struct { // ThroughputProperties: Optional throughput configuration of the container ThroughputProperties *ThroughputProperties }
CreateContainerOptions are options for the CreateContainer operation
type CreateDatabaseOptions ¶
type CreateDatabaseOptions struct { // ThroughputProperties: Optional throughput configuration of the database ThroughputProperties *ThroughputProperties }
CreateDatabaseOptions are options for the CreateDatabase operation
type DataType ¶
type DataType string
DataType defines supported values for data types in Spatial Indexes
const ( // Represents a line. DataTypeString DataType = "String" // Represents a number. DataTypeNumber DataType = "Number" // Represents a point. DataTypePoint DataType = "Point" // Represents a polygon. DataTypePolygon DataType = "Polygon" // Represents a line string. DataTypeLineString DataType = "LineString" // Represents a multi polygon. DataTypeMultiPolygon DataType = "MultiPolygon" )
type DatabaseClient ¶
type DatabaseClient struct {
// contains filtered or unexported fields
}
A DatabaseClient lets you perform read, update, change throughput, and delete database operations.
func (*DatabaseClient) CreateContainer ¶
func (db *DatabaseClient) CreateContainer( ctx context.Context, containerProperties ContainerProperties, o *CreateContainerOptions) (ContainerResponse, error)
CreateContainer creates a container in the Cosmos database. ctx - The context for the request. containerProperties - The properties for the container. o - Options for the create container operation.
Example ¶
package main import ( "context" "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" ) func main() { endpoint, ok := os.LookupEnv("AZURE_COSMOS_ENDPOINT") if !ok { panic("AZURE_COSMOS_ENDPOINT could not be found") } key, ok := os.LookupEnv("AZURE_COSMOS_KEY") if !ok { panic("AZURE_COSMOS_KEY could not be found") } cred, err := azcosmos.NewKeyCredential(key) if err != nil { panic(err) } client, err := azcosmos.NewClientWithKey(endpoint, cred, nil) if err != nil { panic(err) } database, err := client.NewDatabase("databaseName") if err != nil { panic(err) } properties := azcosmos.ContainerProperties{ ID: "aContainer", PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{ Paths: []string{"/myPartitionKey"}, }, } throughput := azcosmos.NewManualThroughputProperties(400) resp, err := database.CreateContainer(context.Background(), properties, &azcosmos.CreateContainerOptions{ThroughputProperties: &throughput}) if err != nil { panic(err) } fmt.Printf("Container created. ActivityId %s", resp.ActivityID) }
Output:
func (*DatabaseClient) Delete ¶
func (db *DatabaseClient) Delete( ctx context.Context, o *DeleteDatabaseOptions) (DatabaseResponse, error)
Delete a Cosmos database. ctx - The context for the request. o - Options for Read operation.
func (*DatabaseClient) ID ¶
func (db *DatabaseClient) ID() string
ID returns the identifier of the Cosmos database.
func (*DatabaseClient) NewContainer ¶
func (db *DatabaseClient) NewContainer(id string) (*ContainerClient, error)
NewContainer returns a struct that represents the container and allows container level operations. id - The id of the container.
func (*DatabaseClient) Read ¶
func (db *DatabaseClient) Read( ctx context.Context, o *ReadDatabaseOptions) (DatabaseResponse, error)
Read obtains the information for a Cosmos database. ctx - The context for the request. o - Options for Read operation.
func (*DatabaseClient) ReadThroughput ¶
func (db *DatabaseClient) ReadThroughput( ctx context.Context, o *ThroughputOptions) (ThroughputResponse, error)
ReadThroughput obtains the provisioned throughput information for the database. ctx - The context for the request. o - Options for the operation.
func (*DatabaseClient) ReplaceThroughput ¶
func (db *DatabaseClient) ReplaceThroughput( ctx context.Context, throughputProperties ThroughputProperties, o *ThroughputOptions) (ThroughputResponse, error)
ReplaceThroughput updates the provisioned throughput for the database. ctx - The context for the request. throughputProperties - The throughput configuration of the database. o - Options for the operation.
type DatabaseProperties ¶
type DatabaseProperties struct { // ID contains the unique id of the database. ID string `json:"id"` // ETag contains the entity etag of the database ETag *azcore.ETag `json:"_etag,omitempty"` // SelfLink contains the self-link of the database SelfLink string `json:"_self,omitempty"` // ResourceID contains the resource id of the database ResourceID string `json:"_rid,omitempty"` // LastModified contains the last modified time of the database LastModified time.Time `json:"_ts,omitempty"` }
DatabaseProperties represents the properties of a database.
func (DatabaseProperties) MarshalJSON ¶
func (tp DatabaseProperties) MarshalJSON() ([]byte, error)
func (*DatabaseProperties) UnmarshalJSON ¶
func (tp *DatabaseProperties) UnmarshalJSON(b []byte) error
type DatabaseResponse ¶
type DatabaseResponse struct { // DatabaseProperties contains the unmarshalled response body in DatabaseProperties format. DatabaseProperties *DatabaseProperties Response }
DatabaseResponse represents the response from a database request.
type DeleteContainerOptions ¶
type DeleteContainerOptions struct{}
DeleteContainerOptions are options for the DeleteContainer operation
type DeleteDatabaseOptions ¶
DeleteDatabaseOptions includes options DeleteDatabase operation.
type ExcludedPath ¶
type ExcludedPath struct { // Path to be excluded. Path string `json:"path"` }
ExcludedPath represents a json path to be excluded from indexing.
type IncludedPath ¶
type IncludedPath struct { // Path to be included. Path string `json:"path"` }
IncludedPath represents a json path to be included in indexing.
type IndexingDirective ¶
type IndexingDirective string
Specifies whether or not the resource in the Azure Cosmos DB database is to be indexed.
const ( // Use any pre-defined/pre-configured defaults. IndexingDirectiveDefault IndexingDirective = "Default" // Index the resource. IndexingDirectiveInclude IndexingDirective = "Include" // Do not index the resource. IndexingDirectiveExclude IndexingDirective = "Exclude" )
func IndexingDirectives ¶
func IndexingDirectives() []IndexingDirective
Returns a list of available indexing directives
func (IndexingDirective) ToPtr ¶
func (c IndexingDirective) ToPtr() *IndexingDirective
type IndexingMode ¶
type IndexingMode string
IndexingMode defines the supported indexing modes in the Azure Cosmos DB service.
const ( // IndexingModeConsistent Index is updated synchronously with a create, update or delete operation. IndexingModeConsistent IndexingMode = "Consistent" // No index is provided. IndexingModeNone IndexingMode = "None" )
func IndexingModeValues ¶
func IndexingModeValues() []IndexingMode
Returns a list of available consistency levels
func (IndexingMode) ToPtr ¶
func (c IndexingMode) ToPtr() *IndexingMode
type IndexingPolicy ¶
type IndexingPolicy struct { // Automatic defines if the indexing policy is automatic or manual. Automatic bool `json:"automatic"` // IndexingMode for the container. IndexingMode IndexingMode `json:"indexingMode,omitempty"` // Paths to be indexed. IncludedPaths []IncludedPath `json:"includedPaths,omitempty"` // Paths to be excluded. ExcludedPaths []ExcludedPath `json:"excludedPaths,omitempty"` // Spatial indexes. SpatialIndexes []SpatialIndex `json:"spatialIndexes,omitempty"` // Spatial indexes. CompositeIndexes [][]CompositeIndex `json:"compositeIndexes,omitempty"` }
IndexingPolicy represents an indexing policy for a container. For more information see https://docs.microsoft.com/azure/cosmos-db/index-policy
type ItemOptions ¶
type ItemOptions struct { // Triggers to be invoked before the operation. PreTriggers []string // Triggers to be invoked after the operation. PostTriggers []string // SessionToken to be used when using Session consistency on the account. // When working with Session consistency, each new write request to Azure Cosmos DB is assigned a new SessionToken. // The client instance will use this token internally with each read/query request to ensure that the set consistency level is maintained. // In some scenarios you need to manage this Session yourself: Consider a web application with multiple nodes, each node will have its own client instance. // If you wanted these nodes to participate in the same session (to be able read your own writes consistently across web tiers), // you would have to send the SessionToken from the response of the write action on one node to the client tier, using a cookie or some other mechanism, and have that token flow back to the web tier for subsequent reads. // If you are using a round-robin load balancer which does not maintain session affinity between requests, such as the Azure Load Balancer,the read could potentially land on a different node to the write request, where the session was created. SessionToken string // ConsistencyLevel overrides the account defined consistency level for this operation. // Consistency can only be relaxed. ConsistencyLevel *ConsistencyLevel // Indexing directive to be applied to the operation. IndexingDirective *IndexingDirective // When EnableContentResponseOnWrite is false will cause the response on write operations to have a null resource. This reduces networking and CPU load by not sending the resource back over the network and serializing it on the client. // The default is false. EnableContentResponseOnWrite bool // IfMatchEtag is used to ensure optimistic concurrency control. // https://docs.microsoft.com/azure/cosmos-db/sql/database-transactions-optimistic-concurrency#optimistic-concurrency-control IfMatchEtag *azcore.ETag }
ItemOptions includes options for operations on items.
type ItemResponse ¶
type ItemResponse struct { // The byte content of the operation response. Value []byte Response // SessionToken contains the value from the session token header to be used on session consistency. SessionToken string }
ItemResponse represents the response from an item request.
type KeyCredential ¶
type KeyCredential struct {
// contains filtered or unexported fields
}
KeyCredential contains an account's name and its primary or secondary key. It is immutable making it shareable and goroutine-safe.
func NewKeyCredential ¶
func NewKeyCredential(accountKey string) (KeyCredential, error)
NewKeyCredential creates an KeyCredential containing the account's primary or secondary key.
func (*KeyCredential) Update ¶
func (c *KeyCredential) Update(accountKey string) error
Update replaces the existing account key with the specified account key.
type PartitionKey ¶
type PartitionKey struct {
// contains filtered or unexported fields
}
PartitionKey represents a logical partition key value.
func NewPartitionKeyBool ¶
func NewPartitionKeyBool(value bool) PartitionKey
NewPartitionKeyBool creates a partition key with a boolean value.
func NewPartitionKeyNumber ¶
func NewPartitionKeyNumber(value float64) PartitionKey
NewPartitionKeyNumber creates a partition key with a numeric value.
func NewPartitionKeyString ¶
func NewPartitionKeyString(value string) PartitionKey
NewPartitionKeyString creates a partition key with a string value.
type PartitionKeyDefinition ¶
type PartitionKeyDefinition struct { // Paths returns the list of partition key paths of the container. Paths []string `json:"paths"` // Version returns the version of the hash partitioning of the container. Version int `json:"version,omitempty"` }
PartitionKeyDefinition represents a partition key definition in the Azure Cosmos DB database service. A partition key definition defines the path for the partition key property.
type ReadContainerOptions ¶
type ReadContainerOptions struct { // PopulateQuotaInfo indicates whether to populate quota info in response headers. PopulateQuotaInfo bool }
ReadContainerOptions includes options for Read
type ReadDatabaseOptions ¶
ReadDatabaseOptions includes options ReadDatabase operation.
type ReplaceContainerOptions ¶
type ReplaceContainerOptions struct{}
ReplaceContainerOptions are options for the ReplaceContainer operation
type Response ¶
type Response struct { // RawResponse contains the underlying HTTP response. RawResponse *http.Response // RequestCharge contains the value from the request charge header. RequestCharge float32 // ActivityID contains the value from the activity header. ActivityID string // ETag contains the value from the ETag header. ETag azcore.ETag }
Response is the base response type for all responses from the Azure Cosmos DB database service. It contains base methods and properties that are common to all responses.
type SpatialIndex ¶
type SpatialIndex struct { // Path for the index. Path string `json:"path"` // SpatialType of the spatial index. SpatialTypes []SpatialType `json:"types"` }
SpatialIndex represents a spatial index.
type SpatialType ¶
type SpatialType string
SpatialType defines supported values for spatial index types in Spatial Indexes
const ( // Represents a point. SpatialTypePoint SpatialType = "Point" // Represents a polygon. SpatialTypePolygon SpatialType = "Polygon" // Represents a line string. SpatialTypeLineString SpatialType = "LineString" // Represents a multi polygon. SpatialTypeMultiPolygon SpatialType = "MultiPolygon" )
func SpatialTypeValues ¶
func SpatialTypeValues() []SpatialType
Returns a list of available data types
func (SpatialType) ToPtr ¶
func (c SpatialType) ToPtr() *SpatialType
type ThroughputOptions ¶
type ThroughputOptions struct { // IfMatchEtag If-Match (ETag) associated with the request. IfMatchEtag *azcore.ETag // IfNoneMatchEtag If-None-Match (ETag) associated with the request. IfNoneMatchEtag *azcore.ETag }
ThroughputOptions includes options for throughput operations.
type ThroughputProperties ¶
type ThroughputProperties struct { // ETag contains the entity etag of the throughput information. ETag *azcore.ETag // LastModified contains the last modified time of the throughput information. LastModified time.Time // contains filtered or unexported fields }
ThroughputProperties describes the throughput configuration of a resource. It must be initialized through the available constructors.
func NewAutoscaleThroughputProperties ¶
func NewAutoscaleThroughputProperties(startingMaxThroughput int32) ThroughputProperties
NewAutoscaleThroughputProperties returns a ThroughputProperties object with the given max throughput on autoscale mode. maxThroughput - the max throughput in RU/s
func NewAutoscaleThroughputPropertiesWithIncrement ¶
func NewAutoscaleThroughputPropertiesWithIncrement(startingMaxThroughput int32, incrementPercentage int32) ThroughputProperties
NewAutoscaleThroughputPropertiesWithIncrement returns a ThroughputProperties object with the given max throughput on autoscale mode. maxThroughput - the max throughput in RU/s incrementPercentage - the auto upgrade max throughput increment percentage
func NewManualThroughputProperties ¶
func NewManualThroughputProperties(throughput int32) ThroughputProperties
NewManualThroughputProperties returns a ThroughputProperties object with the given throughput in manual mode. throughput - the throughput in RU/s
func (*ThroughputProperties) AutoscaleIncrement ¶
func (tp *ThroughputProperties) AutoscaleIncrement() (int32, bool)
AutoscaleIncrement returns the configured percent increment on autoscale mode.
func (*ThroughputProperties) AutoscaleMaxThroughput ¶
func (tp *ThroughputProperties) AutoscaleMaxThroughput() (int32, bool)
AutoscaleMaxThroughput returns the configured max throughput on autoscale mode.
func (*ThroughputProperties) ManualThroughput ¶
func (tp *ThroughputProperties) ManualThroughput() (int32, bool)
ManualThroughput returns the provisioned throughput in manual mode.
func (*ThroughputProperties) MarshalJSON ¶
func (tp *ThroughputProperties) MarshalJSON() ([]byte, error)
func (*ThroughputProperties) UnmarshalJSON ¶
func (tp *ThroughputProperties) UnmarshalJSON(b []byte) error
type ThroughputResponse ¶
type ThroughputResponse struct { // ThroughputProperties contains the unmarshalled response body in ThroughputProperties format. ThroughputProperties *ThroughputProperties Response // IsReplacePending returns the state of a throughput update. IsReplacePending bool // MinThroughput is minimum throughput in measurement of request units per second in the Azure Cosmos service. MinThroughput *int32 }
ThroughputResponse represents the response from a throughput request.
type UniqueKey ¶
type UniqueKey struct { // Paths define a sets of paths which must be unique for each document. Paths []string `json:"paths"` }
UniqueKey represents a unique key for a container. For more information see https://docs.microsoft.com/azure/cosmos-db/unique-keys
type UniqueKeyPolicy ¶
type UniqueKeyPolicy struct { // Automatic defines if the indexing policy is automatic or manual. UniqueKeys []UniqueKey `json:"uniqueKeys"` }
UniqueKeyPolicy represents a unique key policy for a container. For more information see https://docs.microsoft.com/azure/cosmos-db/unique-keys
Source Files ¶
- async_cache.go
- composite_index_order.go
- conflict_resolution_mode.go
- conflict_resolution_policy.go
- consistency_level.go
- cosmos_client.go
- cosmos_client_options.go
- cosmos_container.go
- cosmos_container_properties.go
- cosmos_container_request_options.go
- cosmos_container_response.go
- cosmos_database.go
- cosmos_database_properties.go
- cosmos_database_request_options.go
- cosmos_database_response.go
- cosmos_error.go
- cosmos_headers.go
- cosmos_headers_policy.go
- cosmos_item_request_options.go
- cosmos_item_response.go
- cosmos_offers.go
- cosmos_paths.go
- cosmos_request_options.go
- cosmos_response.go
- data_type.go
- doc.go
- emulator_tests.go
- indexing_directive.go
- indexing_mode.go
- indexing_policy.go
- partition_key.go
- partition_key_definition.go
- resource_type.go
- shared_key_credential.go
- spatial_type.go
- throughput_properties.go
- throughput_request_options.go
- throughput_response.go
- unique_key_policy.go
- version.go