or run

tessl search
Log in

Version

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos@v1.4.1

docs

batch.mdclient.mdconfiguration.mdcontainer.mddatabase.mdindex.mditems.mdpartition-keys.mdpatch.mdquerying.mdthroughput.mdtypes.md
tile.json

tessl/golang-github-com-azure-azure-sdk-for-go-sdk-data-azcosmos

tessl install tessl/golang-github-com-azure-azure-sdk-for-go-sdk-data-azcosmos@1.4.1

Go SDK client library for interacting with Azure Cosmos DB SQL API

container.mddocs/

Container Operations

Container operations allow you to create, read, update, delete, and query containers, as well as manage container-level throughput and configuration settings.

ContainerClient Type

type ContainerClient struct {
    // Has unexported fields.
}

Client for performing container-level operations including item management, querying, and batch operations.

Container Management

CreateContainer

func (db *DatabaseClient) CreateContainer(
    ctx context.Context,
    containerProperties ContainerProperties,
    o *CreateContainerOptions) (ContainerResponse, error)

Creates a new container in the database.

Parameters:

  • ctx - Context for the request
  • containerProperties - Container configuration
  • o - Optional creation options (throughput configuration)

Returns: ContainerResponse containing the created container properties

NewContainer (from DatabaseClient)

func (db *DatabaseClient) NewContainer(id string) (*ContainerClient, error)

Returns a ContainerClient for performing operations on a specific container.

NewContainer (from Client)

func (c *Client) NewContainer(databaseId string, containerId string) (*ContainerClient, error)

Returns a ContainerClient directly from the root Client.

ID

func (c *ContainerClient) ID() string

Returns the identifier of the container.

Read

func (c *ContainerClient) Read(
    ctx context.Context,
    o *ReadContainerOptions) (ContainerResponse, error)

Retrieves container properties and metadata.

Parameters:

  • ctx - Context for the request
  • o - Optional read options

Returns: ContainerResponse containing container properties

Replace

func (c *ContainerClient) Replace(
    ctx context.Context,
    containerProperties ContainerProperties,
    o *ReplaceContainerOptions) (ContainerResponse, error)

Updates container properties (indexing policy, TTL, etc.). Note: Partition key definition cannot be changed.

Parameters:

  • ctx - Context for the request
  • containerProperties - Updated container configuration
  • o - Optional replace options

Returns: ContainerResponse with updated container properties

Delete

func (c *ContainerClient) Delete(
    ctx context.Context,
    o *DeleteContainerOptions) (ContainerResponse, error)

Deletes the container and all its items.

Parameters:

  • ctx - Context for the request
  • o - Optional delete options

Returns: ContainerResponse confirming deletion

Container Queries

NewQueryContainersPager

func (c *DatabaseClient) NewQueryContainersPager(query string, o *QueryContainersOptions) *runtime.Pager[QueryContainersResponse]

Executes a SQL query to retrieve containers in the database.

Parameters:

  • query - The SQL query to execute
  • o - Optional query options

Returns: A pager for iterating through query results

Container Throughput Operations

ReadThroughput

func (c *ContainerClient) ReadThroughput(
    ctx context.Context,
    o *ThroughputOptions) (ThroughputResponse, error)

Retrieves the provisioned throughput configuration for the container.

ReplaceThroughput

func (c *ContainerClient) ReplaceThroughput(
    ctx context.Context,
    throughputProperties ThroughputProperties,
    o *ThroughputOptions) (ThroughputResponse, error)

Updates the provisioned throughput for the container.

Types

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
}

Represents the properties and configuration of a container.

MarshalJSON

func (tp ContainerProperties) MarshalJSON() ([]byte, error)

Implements the json.Marshaler interface.

UnmarshalJSON

func (tp *ContainerProperties) UnmarshalJSON(b []byte) error

Implements the json.Unmarshaler interface.

ContainerResponse

type ContainerResponse struct {
    // ContainerProperties contains the unmarshalled response body in ContainerProperties format.
    ContainerProperties *ContainerProperties
    Response
}

Represents the response from a container operation.

CreateContainerOptions

type CreateContainerOptions struct {
    // ThroughputProperties: Optional throughput configuration of the container
    ThroughputProperties *ThroughputProperties
}

Options for CreateContainer operation.

ReadContainerOptions

type ReadContainerOptions struct {
    // PopulateQuotaInfo indicates whether to populate quota info in response headers.
    PopulateQuotaInfo bool
}

Options for Read operation.

ReplaceContainerOptions

type ReplaceContainerOptions struct{}

Options for ReplaceContainer operation.

DeleteContainerOptions

type DeleteContainerOptions struct{}

Options for DeleteContainer operation.

QueryContainersOptions

type QueryContainersOptions struct {
    // ContinuationToken to be used to continue a previous query execution.
    // Obtained from QueryContainersResponse.ContinuationToken.
    ContinuationToken *string

    // QueryParameters allows execution of parametrized queries.
    // See https://docs.microsoft.com/azure/cosmos-db/sql/sql-query-parameterized-queries
    QueryParameters []QueryParameter
}

Options for querying containers.

QueryContainersResponse

type QueryContainersResponse struct {
    Response
    // ContinuationToken contains the value of the x-ms-continuation header in the response.
    // It can be used to stop a query and resume it later.
    ContinuationToken *string
    // List of containers.
    Containers []ContainerProperties
}

Response from a container query operation.

Usage Examples

Create a Basic Container

import (
    "context"
    "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

database, _ := client.NewDatabase("products")

containerProperties := azcosmos.ContainerProperties{
    ID: "items",
    PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
        Paths: []string{"/category"},
    },
}

response, err := database.CreateContainer(context.Background(), containerProperties, nil)
if err != nil {
    panic(err)
}

fmt.Printf("Created container: %s\n", response.ContainerProperties.ID)

Create Container with Manual Throughput

throughput := azcosmos.NewManualThroughputProperties(400)
options := &azcosmos.CreateContainerOptions{
    ThroughputProperties: &throughput,
}

containerProperties := azcosmos.ContainerProperties{
    ID: "items",
    PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
        Paths: []string{"/category"},
    },
}

response, err := database.CreateContainer(context.Background(), containerProperties, options)
if err != nil {
    panic(err)
}

Create Container with Hierarchical Partition Keys

containerProperties := azcosmos.ContainerProperties{
    ID: "orders",
    PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
        Paths:   []string{"/tenantId", "/userId", "/orderId"},
        Version: 2,
    },
}

response, err := database.CreateContainer(context.Background(), containerProperties, nil)
if err != nil {
    panic(err)
}

Create Container with Time-to-Live (TTL)

defaultTTL := int32(86400) // 24 hours in seconds

containerProperties := azcosmos.ContainerProperties{
    ID: "sessions",
    PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
        Paths: []string{"/userId"},
    },
    DefaultTimeToLive: &defaultTTL,
}

response, err := database.CreateContainer(context.Background(), containerProperties, nil)
if err != nil {
    panic(err)
}

Create Container with Indexing Policy

indexingPolicy := &azcosmos.IndexingPolicy{
    Automatic:    true,
    IndexingMode: azcosmos.IndexingModeConsistent,
    IncludedPaths: []azcosmos.IncludedPath{
        {Path: "/name/?"},
        {Path: "/category/?"},
    },
    ExcludedPaths: []azcosmos.ExcludedPath{
        {Path: "/largeData/*"},
    },
}

containerProperties := azcosmos.ContainerProperties{
    ID: "items",
    PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
        Paths: []string{"/category"},
    },
    IndexingPolicy: indexingPolicy,
}

response, err := database.CreateContainer(context.Background(), containerProperties, nil)
if err != nil {
    panic(err)
}

Create Container with Unique Keys

uniqueKeyPolicy := &azcosmos.UniqueKeyPolicy{
    UniqueKeys: []azcosmos.UniqueKey{
        {Paths: []string{"/email"}},
        {Paths: []string{"/firstName", "/lastName"}},
    },
}

containerProperties := azcosmos.ContainerProperties{
    ID: "users",
    PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
        Paths: []string{"/userId"},
    },
    UniqueKeyPolicy: uniqueKeyPolicy,
}

response, err := database.CreateContainer(context.Background(), containerProperties, nil)
if err != nil {
    panic(err)
}

Read Container Properties

container, _ := database.NewContainer("items")
response, err := container.Read(context.Background(), nil)
if err != nil {
    panic(err)
}

fmt.Printf("Container ID: %s\n", response.ContainerProperties.ID)
fmt.Printf("Partition Key Paths: %v\n", response.ContainerProperties.PartitionKeyDefinition.Paths)

Update Container Indexing Policy

container, _ := database.NewContainer("items")

// Read current properties
readResponse, _ := container.Read(context.Background(), nil)
containerProperties := *readResponse.ContainerProperties

// Update indexing policy
containerProperties.IndexingPolicy = &azcosmos.IndexingPolicy{
    Automatic:    true,
    IndexingMode: azcosmos.IndexingModeConsistent,
    IncludedPaths: []azcosmos.IncludedPath{
        {Path: "/*"},
    },
    ExcludedPaths: []azcosmos.ExcludedPath{},
}

// Replace container
replaceResponse, err := container.Replace(context.Background(), containerProperties, nil)
if err != nil {
    panic(err)
}

fmt.Printf("Updated container, RU charge: %f\n", replaceResponse.RequestCharge)

Delete a Container

container, _ := database.NewContainer("items")
response, err := container.Delete(context.Background(), nil)
if err != nil {
    panic(err)
}

fmt.Printf("Deleted container, RU charge: %f\n", response.RequestCharge)

Query Containers

database, _ := client.NewDatabase("products")

query := "SELECT * FROM c WHERE c.id LIKE 'test%'"
pager := database.NewQueryContainersPager(query, nil)

for pager.More() {
    response, err := pager.NextPage(context.Background())
    if err != nil {
        panic(err)
    }
    
    for _, container := range response.Containers {
        fmt.Printf("Container: %s\n", container.ID)
    }
}

Read Container Throughput

container, _ := database.NewContainer("items")
throughputResponse, err := container.ReadThroughput(context.Background(), nil)
if err != nil {
    panic(err)
}

if manual, ok := throughputResponse.ThroughputProperties.ManualThroughput(); ok {
    fmt.Printf("Manual throughput: %d RU/s\n", manual)
}

if autoscale, ok := throughputResponse.ThroughputProperties.AutoscaleMaxThroughput(); ok {
    fmt.Printf("Autoscale max throughput: %d RU/s\n", autoscale)
}

Update Container Throughput

container, _ := database.NewContainer("items")

// Upgrade from 400 to 1000 RU/s
newThroughput := azcosmos.NewManualThroughputProperties(1000)
response, err := container.ReplaceThroughput(context.Background(), newThroughput, nil)
if err != nil {
    panic(err)
}

fmt.Printf("Updated throughput, RU charge: %f\n", response.RequestCharge)

Convert Manual to Autoscale Throughput

container, _ := database.NewContainer("items")

// Convert to autoscale with max 4000 RU/s
autoscaleThroughput := azcosmos.NewAutoscaleThroughputProperties(4000)
response, err := container.ReplaceThroughput(context.Background(), autoscaleThroughput, nil)
if err != nil {
    panic(err)
}

fmt.Printf("Converted to autoscale\n")