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

items.mddocs/

Item Operations

Item operations allow you to perform CRUD (Create, Read, Update, Delete) operations on documents within a container, including create, read, replace, upsert, delete, and patch operations.

Item CRUD Methods

CreateItem

func (c *ContainerClient) CreateItem(
    ctx context.Context,
    partitionKey PartitionKey,
    item []byte,
    o *ItemOptions) (ItemResponse, error)

Creates a new item in the container. Fails if an item with the same ID already exists.

Parameters:

  • ctx - Context for the request
  • partitionKey - The partition key value for the item
  • item - The item to create as a JSON byte array
  • o - Optional item options

Returns: ItemResponse containing the created item

ReadItem

func (c *ContainerClient) ReadItem(
    ctx context.Context,
    partitionKey PartitionKey,
    itemId string,
    o *ItemOptions) (ItemResponse, error)

Reads an item from the container by its ID and partition key.

Parameters:

  • ctx - Context for the request
  • partitionKey - The partition key value for the item
  • itemId - The ID of the item to read
  • o - Optional item options

Returns: ItemResponse containing the item data

ReplaceItem

func (c *ContainerClient) ReplaceItem(
    ctx context.Context,
    partitionKey PartitionKey,
    itemId string,
    item []byte,
    o *ItemOptions) (ItemResponse, error)

Replaces an existing item in the container. The entire item is replaced.

Parameters:

  • ctx - Context for the request
  • partitionKey - The partition key value for the item
  • itemId - The ID of the item to replace
  • item - The new item content as a JSON byte array
  • o - Optional item options

Returns: ItemResponse containing the replaced item

UpsertItem

func (c *ContainerClient) UpsertItem(
    ctx context.Context,
    partitionKey PartitionKey,
    item []byte,
    o *ItemOptions) (ItemResponse, error)

Creates a new item or replaces an existing item if one with the same ID exists.

Parameters:

  • ctx - Context for the request
  • partitionKey - The partition key value for the item
  • item - The item to upsert as a JSON byte array
  • o - Optional item options

Returns: ItemResponse containing the upserted item

DeleteItem

func (c *ContainerClient) DeleteItem(
    ctx context.Context,
    partitionKey PartitionKey,
    itemId string,
    o *ItemOptions) (ItemResponse, error)

Deletes an item from the container.

Parameters:

  • ctx - Context for the request
  • partitionKey - The partition key value for the item
  • itemId - The ID of the item to delete
  • o - Optional item options

Returns: ItemResponse confirming deletion

PatchItem

func (c *ContainerClient) PatchItem(
    ctx context.Context,
    partitionKey PartitionKey,
    itemId string,
    ops PatchOperations,
    o *ItemOptions) (ItemResponse, error)

Applies partial updates to an item using patch operations. See Patch Operations for details.

Parameters:

  • ctx - Context for the request
  • partitionKey - The partition key value for the item
  • itemId - The ID of the item to patch
  • ops - The patch operations to apply
  • o - Optional item options

Returns: ItemResponse containing the patched item

Types

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.
    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
    // Options for operations in the dedicated gateway.
    DedicatedGatewayRequestOptions *DedicatedGatewayRequestOptions
}

Options for item operations.

Session Token Notes:

  • 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

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
}

Response from an item operation.

Fields:

  • Value - The item content as JSON bytes (nil if EnableContentResponseOnWrite is false)
  • Response - Base response fields (request charge, activity ID, ETag)
  • SessionToken - Session token for Session consistency scenarios

DedicatedGatewayRequestOptions

type DedicatedGatewayRequestOptions struct {
    // Gets or sets the staleness value associated with the request in the Azure Cosmos DB service.
    // For requests where the ConsistencyLevel is ConsistencyLevel.Eventual or ConsistencyLevel.Session,
    // responses from the integrated cache are guaranteed to be no staler than value indicated by this MaxIntegratedCacheStaleness.
    // Cache Staleness is supported in milliseconds granularity. Anything smaller than milliseconds will be ignored.
    MaxIntegratedCacheStaleness *time.Duration
}

Options for operations in the dedicated gateway.

Usage Examples

Create an Item

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

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

item := map[string]interface{}{
    "id":       "item1",
    "category": "electronics",
    "name":     "Laptop",
    "price":    999.99,
}

marshalled, err := json.Marshal(item)
if err != nil {
    panic(err)
}

pk := azcosmos.NewPartitionKeyString("electronics")
response, err := container.CreateItem(context.Background(), pk, marshalled, nil)
if err != nil {
    panic(err)
}

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

Read an Item

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

pk := azcosmos.NewPartitionKeyString("electronics")
response, err := container.ReadItem(context.Background(), pk, "item1", nil)
if err != nil {
    panic(err)
}

var item map[string]interface{}
err = json.Unmarshal(response.Value, &item)
if err != nil {
    panic(err)
}

fmt.Printf("Item name: %s\n", item["name"])

Replace an Item

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

pk := azcosmos.NewPartitionKeyString("electronics")

// Read existing item
readResponse, _ := container.ReadItem(context.Background(), pk, "item1", nil)
var item map[string]interface{}
json.Unmarshal(readResponse.Value, &item)

// Modify and replace
item["price"] = 899.99
marshalled, _ := json.Marshal(item)

response, err := container.ReplaceItem(context.Background(), pk, "item1", marshalled, nil)
if err != nil {
    panic(err)
}

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

Upsert an Item

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

item := map[string]interface{}{
    "id":       "item1",
    "category": "electronics",
    "name":     "Laptop Pro",
    "price":    1299.99,
}

marshalled, _ := json.Marshal(item)
pk := azcosmos.NewPartitionKeyString("electronics")

response, err := container.UpsertItem(context.Background(), pk, marshalled, nil)
if err != nil {
    panic(err)
}

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

Delete an Item

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

pk := azcosmos.NewPartitionKeyString("electronics")
response, err := container.DeleteItem(context.Background(), pk, "item1", nil)
if err != nil {
    panic(err)
}

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

Create Item with Hierarchical Partition Key

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

item := map[string]interface{}{
    "id":       "order123",
    "tenantId": "tenant1",
    "userId":   "user456",
    "orderId":  "order123",
    "total":    150.00,
}

marshalled, _ := json.Marshal(item)

// Create hierarchical partition key
pk := azcosmos.NewPartitionKeyString("tenant1").
    AppendString("user456").
    AppendString("order123")

response, err := container.CreateItem(context.Background(), pk, marshalled, nil)
if err != nil {
    panic(err)
}

Optimistic Concurrency with ETag

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

pk := azcosmos.NewPartitionKeyString("electronics")

// Read item to get ETag
readResponse, _ := container.ReadItem(context.Background(), pk, "item1", nil)
var item map[string]interface{}
json.Unmarshal(readResponse.Value, &item)

// Modify item
item["price"] = 799.99
marshalled, _ := json.Marshal(item)

// Replace only if ETag matches (no one else modified it)
options := &azcosmos.ItemOptions{
    IfMatchEtag: &readResponse.ETag,
}

response, err := container.ReplaceItem(context.Background(), pk, "item1", marshalled, options)
if err != nil {
    // Will fail with 412 Precondition Failed if item was modified
    fmt.Printf("Item was modified by another process\n")
} else {
    fmt.Printf("Successfully updated item\n")
}

Disable Content Response on Write

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

item := map[string]interface{}{
    "id":       "item1",
    "category": "electronics",
    "name":     "Laptop",
}

marshalled, _ := json.Marshal(item)
pk := azcosmos.NewPartitionKeyString("electronics")

options := &azcosmos.ItemOptions{
    EnableContentResponseOnWrite: false,
}

response, err := container.CreateItem(context.Background(), pk, marshalled, options)
if err != nil {
    panic(err)
}

// response.Value will be nil, reducing network overhead
fmt.Printf("Created item with minimal response, RU charge: %f\n", response.RequestCharge)

Override Consistency Level

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

pk := azcosmos.NewPartitionKeyString("electronics")

// Read with relaxed consistency
eventual := azcosmos.ConsistencyLevelEventual
options := &azcosmos.ItemOptions{
    ConsistencyLevel: &eventual,
}

response, err := container.ReadItem(context.Background(), pk, "item1", options)
if err != nil {
    panic(err)
}

fmt.Printf("Read item with Eventual consistency\n")

Use Session Token Across Requests

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

item := map[string]interface{}{
    "id":       "item1",
    "category": "electronics",
    "name":     "Laptop",
}

marshalled, _ := json.Marshal(item)
pk := azcosmos.NewPartitionKeyString("electronics")

// Create item
createResponse, _ := container.CreateItem(context.Background(), pk, marshalled, nil)
sessionToken := createResponse.SessionToken

// Read with session token to ensure consistency
readOptions := &azcosmos.ItemOptions{
    SessionToken: sessionToken,
}

readResponse, err := container.ReadItem(context.Background(), pk, "item1", readOptions)
if err != nil {
    panic(err)
}

fmt.Printf("Read item with session consistency\n")

Exclude Item from Indexing

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

item := map[string]interface{}{
    "id":       "temp-item",
    "category": "electronics",
    "data":     "large binary data...",
}

marshalled, _ := json.Marshal(item)
pk := azcosmos.NewPartitionKeyString("electronics")

exclude := azcosmos.IndexingDirectiveExclude
options := &azcosmos.ItemOptions{
    IndexingDirective: &exclude,
}

response, err := container.CreateItem(context.Background(), pk, marshalled, options)
if err != nil {
    panic(err)
}

fmt.Printf("Created item without indexing\n")

Use Pre and Post Triggers

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

item := map[string]interface{}{
    "id":       "item1",
    "category": "electronics",
    "name":     "Laptop",
}

marshalled, _ := json.Marshal(item)
pk := azcosmos.NewPartitionKeyString("electronics")

options := &azcosmos.ItemOptions{
    PreTriggers:  []string{"validateItem"},
    PostTriggers: []string{"updateMetadata"},
}

response, err := container.CreateItem(context.Background(), pk, marshalled, options)
if err != nil {
    panic(err)
}

fmt.Printf("Created item with triggers\n")

Use Dedicated Gateway Cache

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

pk := azcosmos.NewPartitionKeyString("electronics")

staleness := 5 * time.Minute
options := &azcosmos.ItemOptions{
    DedicatedGatewayRequestOptions: &azcosmos.DedicatedGatewayRequestOptions{
        MaxIntegratedCacheStaleness: &staleness,
    },
}

response, err := container.ReadItem(context.Background(), pk, "item1", options)
if err != nil {
    panic(err)
}

fmt.Printf("Read item from cache (max 5 min staleness)\n")