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
Query operations allow you to execute SQL queries against databases, containers, and items with support for parameterization, pagination, and limited cross-partition queries.
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 executepartitionKey - The partition key to scope the query. Pass NewPartitionKey() for cross-partition querieso - Optional query optionsReturns: A pager for iterating through query results
Cross-Partition Query Notes:
NewPartitionKey() to indicate that query WHERE clauses will specify which partitions to queryfunc (c *DatabaseClient) NewQueryContainersPager(query string, o *QueryContainersOptions) *runtime.Pager[QueryContainersResponse]Executes a SQL query to retrieve containers in a database.
func (c *Client) NewQueryDatabasesPager(query string, o *QueryDatabasesOptions) *runtime.Pager[QueryDatabasesResponse]Executes a SQL query to retrieve databases in an account.
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.
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 @.
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.
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.
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.
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.
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.
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"])
}
}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"])
}
}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"])
}
}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)
}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))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)
}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)
}
}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)
}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"])
}
}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"])
}
}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"])
}
}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)
}
}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)
}
}