tessl install tessl/golang-github-com-azure-azure-sdk-for-go-sdk-data-azcosmos@1.4.1Go SDK client library for interacting with Azure Cosmos DB SQL API
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.
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 requestpartitionKey - The partition key value for the itemitem - The item to create as a JSON byte arrayo - Optional item optionsReturns: ItemResponse containing the created item
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 requestpartitionKey - The partition key value for the itemitemId - The ID of the item to reado - Optional item optionsReturns: ItemResponse containing the item data
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 requestpartitionKey - The partition key value for the itemitemId - The ID of the item to replaceitem - The new item content as a JSON byte arrayo - Optional item optionsReturns: ItemResponse containing the replaced item
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 requestpartitionKey - The partition key value for the itemitem - The item to upsert as a JSON byte arrayo - Optional item optionsReturns: ItemResponse containing the upserted item
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 requestpartitionKey - The partition key value for the itemitemId - The ID of the item to deleteo - Optional item optionsReturns: ItemResponse confirming deletion
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 requestpartitionKey - The partition key value for the itemitemId - The ID of the item to patchops - The patch operations to applyo - Optional item optionsReturns: ItemResponse containing the patched item
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:
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 scenariostype 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.
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)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"])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)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)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)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)
}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")
}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)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")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")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")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")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")