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

querying.mddocs/

Query Operations

Query operations allow you to execute SQL queries against databases, containers, and items with support for parameterization, pagination, and limited cross-partition queries.

Query Methods

NewQueryItemsPager

func (c *ContainerClient) NewQueryItemsPager(
    query string,
    partitionKey PartitionKey,
    o *QueryOptions) *runtime.Pager[QueryItemsResponse]

Executes a SQL query for items in a container. Supports single-partition queries and limited cross-partition queries.

Parameters:

  • query - The SQL query to execute
  • partitionKey - The partition key to scope the query. Pass NewPartitionKey() for cross-partition queries
  • o - Optional query options

Returns: A pager for iterating through query results

Cross-Partition Query Notes:

  • Specify an empty list of partition keys by passing NewPartitionKey() to indicate that query WHERE clauses will specify which partitions to query
  • Limited cross partition queries ARE possible with the Go SDK
  • If you specify partition keys in the parameter, you must specify ALL partition keys that the container has (in case of hierarchical partitioning)
  • The Gateway API can only perform a LIMITED set of cross-partition queries (simple projections and filtering)
  • Gateway may return pages of inconsistent size, or even empty pages (while still having a non-nil continuation token)
  • See: https://learn.microsoft.com/rest/api/cosmos-db/querying-cosmosdb-resources-using-the-rest-api#queries-that-cannot-be-served-by-gateway

NewQueryContainersPager

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

Executes a SQL query to retrieve containers in a database.

NewQueryDatabasesPager

func (c *Client) NewQueryDatabasesPager(query string, o *QueryDatabasesOptions) *runtime.Pager[QueryDatabasesResponse]

Executes a SQL query to retrieve databases in an account.

Types

QueryOptions

type QueryOptions struct {
    // 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
    // PopulateIndexMetrics is used to obtain the index metrics to understand how the query engine used existing indexes and how it could use potential new indexes.
    // Please note that this options will incur overhead, so it should be enabled only when debugging slow queries and not in production.
    PopulateIndexMetrics bool
    // ResponseContinuationTokenLimitInKB is used to limit the length of continuation token in the query response. Valid values are >= 0.
    ResponseContinuationTokenLimitInKB int32
    // PageSizeHint determines the maximum number of items to be retrieved in a query result page.
    // '-1' Used for dynamic page size. This is a maximum. Query can return 0 items in the page.
    PageSizeHint int32
    // EnableScanInQuery Allow scan on the queries which couldn't be served as indexing was opted out on the requested paths.
    EnableScanInQuery bool
    // ContinuationToken to be used to continue a previous query execution.
    // Obtained from QueryItemsResponse.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 operations in the dedicated gateway.
    DedicatedGatewayRequestOptions *DedicatedGatewayRequestOptions
    // EnableCrossPartitionQuery configures the behavior of the query engine when executing queries.
    // If set to true, the query engine will set the 'x-ms-documentdb-query-enablecrosspartition' header to true for cross-partition queries.
    // If set to false, cross-partition queries will be rejected.
    // The default value, if this is not set, is true.
    EnableCrossPartitionQuery *bool
}

Options for query operations on items.

QueryParameter

type QueryParameter struct {
    // Name represents the name of the parameter in the parametrized query.
    Name string `json:"name"`
    // Value represents the value of the parameter in the parametrized query.
    Value any `json:"value"`
}

Represents a parameter for a parameterized query. Parameter names must start with @.

QueryItemsResponse

type QueryItemsResponse 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
    // Contains the query metrics related to the query execution
    QueryMetrics *string
    // IndexMetrics contains the index utilization metrics if QueryOptions.PopulateIndexMetrics = true
    IndexMetrics *string
    // List of items.
    Items [][]byte
}

Response from an item query 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.

QueryDatabasesOptions

type QueryDatabasesOptions struct {
    // ContinuationToken to be used to continue a previous query execution.
    // Obtained from QueryDatabasesResponse.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 databases.

QueryDatabasesResponse

type QueryDatabasesResponse 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 databases.
    Databases []DatabaseProperties
}

Response from a database query operation.

Usage Examples

Basic Query

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

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

query := "SELECT * FROM c WHERE c.category = 'electronics'"
pk := azcosmos.NewPartitionKeyString("electronics")

pager := container.NewQueryItemsPager(query, pk, nil)

for pager.More() {
    response, err := pager.NextPage(context.Background())
    if err != nil {
        panic(err)
    }
    
    for _, itemBytes := range response.Items {
        var item map[string]interface{}
        json.Unmarshal(itemBytes, &item)
        fmt.Printf("Item: %s\n", item["name"])
    }
}

Parameterized Query

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

query := "SELECT * FROM c WHERE c.category = @category AND c.price > @minPrice"
pk := azcosmos.NewPartitionKeyString("electronics")

options := &azcosmos.QueryOptions{
    QueryParameters: []azcosmos.QueryParameter{
        {Name: "@category", Value: "electronics"},
        {Name: "@minPrice", Value: 500.0},
    },
}

pager := container.NewQueryItemsPager(query, pk, options)

for pager.More() {
    response, err := pager.NextPage(context.Background())
    if err != nil {
        panic(err)
    }
    
    for _, itemBytes := range response.Items {
        var item map[string]interface{}
        json.Unmarshal(itemBytes, &item)
        fmt.Printf("Item: %s, Price: %.2f\n", item["name"], item["price"])
    }
}

Cross-Partition Query

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

// Query across all partitions
query := "SELECT * FROM c WHERE c.price > 1000"
pk := azcosmos.NewPartitionKey() // Empty partition key for cross-partition query

pager := container.NewQueryItemsPager(query, pk, nil)

for pager.More() {
    response, err := pager.NextPage(context.Background())
    if err != nil {
        panic(err)
    }
    
    fmt.Printf("Page with %d items\n", len(response.Items))
    
    for _, itemBytes := range response.Items {
        var item map[string]interface{}
        json.Unmarshal(itemBytes, &item)
        fmt.Printf("Item: %s from partition: %s\n", item["name"], item["category"])
    }
}

Query with Page Size

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

query := "SELECT * FROM c"
pk := azcosmos.NewPartitionKeyString("electronics")

options := &azcosmos.QueryOptions{
    PageSizeHint: 10, // Request max 10 items per page
}

pager := container.NewQueryItemsPager(query, pk, options)

pageCount := 0
for pager.More() {
    response, err := pager.NextPage(context.Background())
    if err != nil {
        panic(err)
    }
    
    pageCount++
    fmt.Printf("Page %d: %d items, RU charge: %f\n", 
        pageCount, len(response.Items), response.RequestCharge)
}

Query with Continuation Token

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

query := "SELECT * FROM c"
pk := azcosmos.NewPartitionKeyString("electronics")

// First batch
options := &azcosmos.QueryOptions{
    PageSizeHint: 100,
}

pager := container.NewQueryItemsPager(query, pk, options)
response1, _ := pager.NextPage(context.Background())

// Save continuation token
continuationToken := response1.ContinuationToken

// Later, resume from continuation token
resumeOptions := &azcosmos.QueryOptions{
    ContinuationToken: continuationToken,
    PageSizeHint:      100,
}

pager2 := container.NewQueryItemsPager(query, pk, resumeOptions)
response2, _ := pager2.NextPage(context.Background())

fmt.Printf("Resumed query with %d items\n", len(response2.Items))

Query with Index Metrics

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

query := "SELECT * FROM c WHERE c.name = 'Laptop' ORDER BY c.price"
pk := azcosmos.NewPartitionKeyString("electronics")

options := &azcosmos.QueryOptions{
    PopulateIndexMetrics: true,
}

pager := container.NewQueryItemsPager(query, pk, options)
response, _ := pager.NextPage(context.Background())

if response.IndexMetrics != nil {
    fmt.Printf("Index Metrics: %s\n", *response.IndexMetrics)
    fmt.Printf("Query Metrics: %s\n", *response.QueryMetrics)
}

Query with Projection

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

query := "SELECT c.id, c.name, c.price FROM c WHERE c.category = 'electronics'"
pk := azcosmos.NewPartitionKeyString("electronics")

pager := container.NewQueryItemsPager(query, pk, nil)

for pager.More() {
    response, err := pager.NextPage(context.Background())
    if err != nil {
        panic(err)
    }
    
    for _, itemBytes := range response.Items {
        var item struct {
            ID    string  `json:"id"`
            Name  string  `json:"name"`
            Price float64 `json:"price"`
        }
        json.Unmarshal(itemBytes, &item)
        fmt.Printf("%s: $%.2f\n", item.Name, item.Price)
    }
}

Query with Aggregation

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

query := "SELECT COUNT(1) as count, AVG(c.price) as avgPrice FROM c WHERE c.category = @category"
pk := azcosmos.NewPartitionKeyString("electronics")

options := &azcosmos.QueryOptions{
    QueryParameters: []azcosmos.QueryParameter{
        {Name: "@category", Value: "electronics"},
    },
}

pager := container.NewQueryItemsPager(query, pk, options)
response, _ := pager.NextPage(context.Background())

if len(response.Items) > 0 {
    var result struct {
        Count    int     `json:"count"`
        AvgPrice float64 `json:"avgPrice"`
    }
    json.Unmarshal(response.Items[0], &result)
    fmt.Printf("Count: %d, Average Price: %.2f\n", result.Count, result.AvgPrice)
}

Query with ORDER BY

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

query := "SELECT * FROM c WHERE c.category = 'electronics' ORDER BY c.price DESC"
pk := azcosmos.NewPartitionKeyString("electronics")

pager := container.NewQueryItemsPager(query, pk, nil)

for pager.More() {
    response, err := pager.NextPage(context.Background())
    if err != nil {
        panic(err)
    }
    
    for _, itemBytes := range response.Items {
        var item map[string]interface{}
        json.Unmarshal(itemBytes, &item)
        fmt.Printf("%s: $%.2f\n", item["name"], item["price"])
    }
}

Query with JOIN

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

// Self-join to expand array elements
query := `
    SELECT c.id, c.name, tag
    FROM c
    JOIN tag IN c.tags
    WHERE c.category = 'electronics'
`
pk := azcosmos.NewPartitionKeyString("electronics")

pager := container.NewQueryItemsPager(query, pk, nil)

for pager.More() {
    response, err := pager.NextPage(context.Background())
    if err != nil {
        panic(err)
    }
    
    for _, itemBytes := range response.Items {
        var item map[string]interface{}
        json.Unmarshal(itemBytes, &item)
        fmt.Printf("%s - Tag: %s\n", item["name"], item["tag"])
    }
}

Query Hierarchical Partition Keys

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

query := "SELECT * FROM c WHERE c.userId = @userId"

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

options := &azcosmos.QueryOptions{
    QueryParameters: []azcosmos.QueryParameter{
        {Name: "@userId", Value: "user456"},
    },
}

pager := container.NewQueryItemsPager(query, pk, options)

for pager.More() {
    response, err := pager.NextPage(context.Background())
    if err != nil {
        panic(err)
    }
    
    for _, itemBytes := range response.Items {
        var order map[string]interface{}
        json.Unmarshal(itemBytes, &order)
        fmt.Printf("Order: %s\n", order["id"])
    }
}

Query Databases

client, _ := azcosmos.NewClientWithKey("https://myaccount.documents.azure.com:443/", cred, nil)

query := "SELECT * FROM c WHERE STARTSWITH(c.id, 'prod')"
pager := client.NewQueryDatabasesPager(query, nil)

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

Query Containers

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

query := "SELECT * FROM c"
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)
        fmt.Printf("Partition Keys: %v\n", container.PartitionKeyDefinition.Paths)
    }
}