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

types.mddocs/

Response Types & Options

Common response types, option structures, enumerations, and constants used throughout the azcosmos SDK.

Base Response 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
}

Base response type for all operations. Contains common fields present in all responses.

Fields:

  • RawResponse - The underlying HTTP response for advanced scenarios
  • RequestCharge - The number of Request Units (RUs) consumed by the operation
  • ActivityID - Unique identifier for the request for diagnostics and support
  • ETag - Entity tag for optimistic concurrency control

Consistency Levels

ConsistencyLevel

type ConsistencyLevel string

Consistency levels supported by Azure Cosmos DB.

Constants:

const (
    ConsistencyLevelStrong           ConsistencyLevel = "Strong"
    ConsistencyLevelBoundedStaleness ConsistencyLevel = "BoundedStaleness"
    ConsistencyLevelSession          ConsistencyLevel = "Session"
    ConsistencyLevelEventual         ConsistencyLevel = "Eventual"
    ConsistencyLevelConsistentPrefix ConsistencyLevel = "ConsistentPrefix"
)
  • ConsistencyLevelStrong - Strongest consistency, linearizability guarantee
  • ConsistencyLevelBoundedStaleness - Reads lag behind writes by at most K versions or T time
  • ConsistencyLevelSession - Consistent within a session (default)
  • ConsistencyLevelEventual - Weakest consistency, eventual convergence
  • ConsistencyLevelConsistentPrefix - Reads never see out-of-order writes

ConsistencyLevelValues

func ConsistencyLevelValues() []ConsistencyLevel

Returns a list of available consistency levels.

ToPtr

func (c ConsistencyLevel) ToPtr() *ConsistencyLevel

Returns a pointer to the ConsistencyLevel.

Data Types

DataType

type DataType string

Data types supported in spatial indexes.

Constants:

const (
    // Represents a string.
    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"
)

DataTypeValues

func DataTypeValues() []DataType

Returns a list of available data types.

ToPtr

func (c DataType) ToPtr() *DataType

Returns a pointer to the DataType.

Usage Examples

Working with Request Charges

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

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

// Track RU consumption for operations
item := map[string]interface{}{"id": "item1", "category": "electronics"}
marshalled, _ := json.Marshal(item)
pk := azcosmos.NewPartitionKeyString("electronics")

createResponse, _ := container.CreateItem(context.Background(), pk, marshalled, nil)
fmt.Printf("Create RU charge: %f\n", createResponse.RequestCharge)

readResponse, _ := container.ReadItem(context.Background(), pk, "item1", nil)
fmt.Printf("Read RU charge: %f\n", readResponse.RequestCharge)

// Query RU charges are cumulative across pages
query := "SELECT * FROM c"
totalRUs := 0.0

pager := container.NewQueryItemsPager(query, pk, nil)
for pager.More() {
    response, _ := pager.NextPage(context.Background())
    totalRUs += float64(response.RequestCharge)
}

fmt.Printf("Total query RU charge: %f\n", totalRUs)

Using Activity IDs for Diagnostics

container, _ := database.NewContainer("items")
pk := azcosmos.NewPartitionKeyString("electronics")

response, err := container.ReadItem(context.Background(), pk, "item1", nil)
if err != nil {
    // Include activity ID when contacting support
    fmt.Printf("Error occurred. Activity ID: %s\n", response.ActivityID)
    panic(err)
}

// Log activity ID for audit trail
fmt.Printf("Operation successful. Activity ID: %s\n", response.ActivityID)

Working with ETags

container, _ := database.NewContainer("items")
pk := azcosmos.NewPartitionKeyString("electronics")

// Read item to get ETag
readResponse, _ := container.ReadItem(context.Background(), pk, "item1", nil)
fmt.Printf("Current ETag: %s\n", readResponse.ETag)

// Conditional update using ETag
var item map[string]interface{}
json.Unmarshal(readResponse.Value, &item)
item["price"] = 899.99
marshalled, _ := json.Marshal(item)

options := &azcosmos.ItemOptions{
    IfMatchEtag: &readResponse.ETag, // Only update if ETag matches
}

replaceResponse, err := container.ReplaceItem(context.Background(), pk, "item1", marshalled, options)
if err != nil {
    fmt.Printf("Item was modified by another process\n")
} else {
    fmt.Printf("Updated successfully. New ETag: %s\n", replaceResponse.ETag)
}

Accessing Raw HTTP Response

container, _ := database.NewContainer("items")
pk := azcosmos.NewPartitionKeyString("electronics")

response, _ := container.ReadItem(context.Background(), pk, "item1", nil)

// Access HTTP headers
fmt.Printf("Status Code: %d\n", response.RawResponse.StatusCode)
fmt.Printf("Content-Type: %s\n", response.RawResponse.Header.Get("Content-Type"))
fmt.Printf("x-ms-request-charge: %s\n", response.RawResponse.Header.Get("x-ms-request-charge"))

// Access other response headers
for key, values := range response.RawResponse.Header {
    fmt.Printf("%s: %v\n", key, values)
}

Consistency Level Examples

container, _ := database.NewContainer("items")
pk := azcosmos.NewPartitionKeyString("electronics")

// Strong consistency read
strong := azcosmos.ConsistencyLevelStrong
strongOptions := &azcosmos.ItemOptions{
    ConsistencyLevel: &strong,
}
strongResponse, _ := container.ReadItem(context.Background(), pk, "item1", strongOptions)

// Eventual consistency read (lower RU cost)
eventual := azcosmos.ConsistencyLevelEventual
eventualOptions := &azcosmos.ItemOptions{
    ConsistencyLevel: &eventual,
}
eventualResponse, _ := container.ReadItem(context.Background(), pk, "item1", eventualOptions)

fmt.Printf("Strong consistency RU: %f\n", strongResponse.RequestCharge)
fmt.Printf("Eventual consistency RU: %f\n", eventualResponse.RequestCharge)

Consistency Level Hierarchy

// Account-level consistency: Session (default)
// Can relax to Eventual or ConsistentPrefix
// Cannot strengthen to BoundedStaleness or Strong

// Valid: Relax from Session to Eventual
eventual := azcosmos.ConsistencyLevelEventual
options := &azcosmos.ItemOptions{
    ConsistencyLevel: &eventual,
}

// Invalid: Cannot strengthen from Session to Strong
// This will use Session consistency instead
strong := azcosmos.ConsistencyLevelStrong
invalidOptions := &azcosmos.ItemOptions{
    ConsistencyLevel: &strong, // Will be ignored if account is Session
}

Query Options Examples

container, _ := database.NewContainer("items")
pk := azcosmos.NewPartitionKeyString("electronics")

// Comprehensive query options
options := &azcosmos.QueryOptions{
    PageSizeHint:                       100,
    PopulateIndexMetrics:               true,
    ResponseContinuationTokenLimitInKB: 4,
    EnableScanInQuery:                  false,
    QueryParameters: []azcosmos.QueryParameter{
        {Name: "@category", Value: "electronics"},
        {Name: "@minPrice", Value: 500.0},
    },
}

query := "SELECT * FROM c WHERE c.category = @category AND c.price > @minPrice"
pager := container.NewQueryItemsPager(query, pk, options)

response, _ := pager.NextPage(context.Background())
if response.IndexMetrics != nil {
    fmt.Printf("Index Metrics: %s\n", *response.IndexMetrics)
}

Item Options Examples

container, _ := database.NewContainer("items")
pk := azcosmos.NewPartitionKeyString("electronics")

item := map[string]interface{}{"id": "item1", "category": "electronics"}
marshalled, _ := json.Marshal(item)

// Comprehensive item options
options := &azcosmos.ItemOptions{
    EnableContentResponseOnWrite: true,
    PreTriggers:                  []string{"validateItem"},
    PostTriggers:                 []string{"updateMetadata"},
    SessionToken:                 sessionToken,
    IndexingDirective:            &azcosmos.IndexingDirectiveInclude,
}

response, _ := container.CreateItem(context.Background(), pk, marshalled, options)

Batch Options Examples

container, _ := database.NewContainer("items")
pk := azcosmos.NewPartitionKeyString("electronics")

batch := container.NewTransactionalBatch(pk)
// Add operations...

options := &azcosmos.TransactionalBatchOptions{
    SessionToken:                 "session-token-value",
    EnableContentResponseOnWrite: true,
}

response, _ := container.ExecuteTransactionalBatch(context.Background(), batch, options)

// Access session token from response
fmt.Printf("New session token: %s\n", response.SessionToken)

Dedicated Gateway Cache Options

container, _ := database.NewContainer("items")
pk := azcosmos.NewPartitionKeyString("electronics")

// Allow up to 5 minutes of staleness from cache
staleness := 5 * time.Minute
options := &azcosmos.ItemOptions{
    DedicatedGatewayRequestOptions: &azcosmos.DedicatedGatewayRequestOptions{
        MaxIntegratedCacheStaleness: &staleness,
    },
}

response, _ := container.ReadItem(context.Background(), pk, "item1", options)
fmt.Printf("Read from cache (max 5 min staleness)\n")

Enum Helper Functions

// Get all available consistency levels
levels := azcosmos.ConsistencyLevelValues()
for _, level := range levels {
    fmt.Printf("Consistency Level: %s\n", level)
}

// Get all indexing modes
modes := azcosmos.IndexingModeValues()
for _, mode := range modes {
    fmt.Printf("Indexing Mode: %s\n", mode)
}

// Get all indexing directives
directives := azcosmos.IndexingDirectives()
for _, directive := range directives {
    fmt.Printf("Indexing Directive: %s\n", directive)
}

// Get all composite index orders
orders := azcosmos.CompositeIndexOrderValues()
for _, order := range orders {
    fmt.Printf("Composite Index Order: %s\n", order)
}

// Get all conflict resolution modes
modes := azcosmos.ConflictResolutionModeValues()
for _, mode := range modes {
    fmt.Printf("Conflict Resolution Mode: %s\n", mode)
}

// Get all spatial types
types := azcosmos.SpatialTypeValues()
for _, t := range types {
    fmt.Printf("Spatial Type: %s\n", t)
}

// Get all data types
dataTypes := azcosmos.DataTypeValues()
for _, dt := range dataTypes {
    fmt.Printf("Data Type: %s\n", dt)
}

Pointer Helpers

// Use ToPtr() for optional enum fields
indexingMode := azcosmos.IndexingModeConsistent
indexingPolicy := &azcosmos.IndexingPolicy{
    Automatic:    true,
    IndexingMode: indexingMode.ToPtr(),
}

// Use ToPtr() for consistency level
consistencyLevel := azcosmos.ConsistencyLevelEventual
options := &azcosmos.ItemOptions{
    ConsistencyLevel: consistencyLevel.ToPtr(),
}

// Use ToPtr() for indexing directive
directive := azcosmos.IndexingDirectiveExclude
itemOptions := &azcosmos.ItemOptions{
    IndexingDirective: directive.ToPtr(),
}

Error Handling with Response Information

container, _ := database.NewContainer("items")
pk := azcosmos.NewPartitionKeyString("electronics")

response, err := container.ReadItem(context.Background(), pk, "nonexistent", nil)
if err != nil {
    // Check status code from raw response
    if response.RawResponse != nil {
        switch response.RawResponse.StatusCode {
        case 404:
            fmt.Printf("Item not found\n")
        case 429:
            fmt.Printf("Rate limited. Retry after: %s\n", 
                response.RawResponse.Header.Get("x-ms-retry-after-ms"))
        case 412:
            fmt.Printf("Precondition failed (ETag mismatch)\n")
        default:
            fmt.Printf("Error: %d - %s\n", response.RawResponse.StatusCode, err)
        }
    }
    
    // Activity ID for support
    fmt.Printf("Activity ID for support: %s\n", response.ActivityID)
}

Complete Response Inspection

container, _ := database.NewContainer("items")
pk := azcosmos.NewPartitionKeyString("electronics")

response, _ := container.ReadItem(context.Background(), pk, "item1", nil)

// Base response information
fmt.Printf("Request Charge: %f RU\n", response.RequestCharge)
fmt.Printf("Activity ID: %s\n", response.ActivityID)
fmt.Printf("ETag: %s\n", response.ETag)

// Item-specific information
fmt.Printf("Session Token: %s\n", *response.SessionToken)
fmt.Printf("Item Data: %s\n", string(response.Value))

// HTTP response information
fmt.Printf("Status Code: %d\n", response.RawResponse.StatusCode)
fmt.Printf("Headers:\n")
for key, values := range response.RawResponse.Header {
    fmt.Printf("  %s: %v\n", key, values)
}