Događaj
Izgradite inteligentne aplikacije
17. mar 21 - 21. mar 10
Pridružite se seriji sastanaka kako biste izgradili skalabilna AI rešenja zasnovana na stvarnim slučajevima korišćenja sa kolegama programerima i stručnjacima.
Registrujte se odmahOvaj pregledač više nije podržan.
Nadogradite na Microsoft Edge biste iskoristili najnovije funkcije, bezbednosne ispravke i tehničku podršku.
In this quickstart, you deploy a basic Azure Cosmos DB for NoSQL application using the Azure SDK for Go. Azure Cosmos DB for NoSQL is a schemaless data store allowing applications to store unstructured data in the cloud. Query data in your containers and perform common operations on individual items using the Azure SDK for Go.
API reference documentation | Library source code | Package (Go) | Azure Developer CLI
Go
1.21 or newerIf you don't have an Azure account, create a free account before you begin.
Use the Azure Developer CLI (azd
) to create an Azure Cosmos DB for NoSQL account and deploy a containerized sample application. The sample application uses the client library to manage, create, read, and query sample data.
Open a terminal in an empty directory.
If you're not already authenticated, authenticate to the Azure Developer CLI using azd auth login
. Follow the steps specified by the tool to authenticate to the CLI using your preferred Azure credentials.
azd auth login
Use azd init
to initialize the project.
azd init --template cosmos-db-nosql-go-quickstart
During initialization, configure a unique environment name.
Deploy the Azure Cosmos DB account using azd up
. The Bicep templates also deploy a sample web application.
azd up
During the provisioning process, select your subscription, desired location, and target resource group. Wait for the provisioning process to complete. The process can take approximately five minutes.
Once the provisioning of your Azure resources is done, a URL to the running web application is included in the output.
Deploying services (azd deploy)
(✓) Done: Deploying service web
- Endpoint: <https://[container-app-sub-domain].azurecontainerapps.io>
SUCCESS: Your application was provisioned and deployed to Azure in 5 minutes 0 seconds.
Use the URL in the console to navigate to your web application in the browser. Observe the output of the running app.
The client library is available through Go, as the azcosmos
package.
Open a terminal and navigate to the /src
folder.
cd ./src
If not already installed, install the azcosmos
package using go install
.
go install github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos
Also, install the azidentity
package if not already installed.
go install github.com/Azure/azure-sdk-for-go/sdk/azidentity
Open and review the src/go.mod file to validate that the github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos
and github.com/Azure/azure-sdk-for-go/sdk/azidentity
entries both exist.
Name | Description |
---|---|
CosmosClient |
This class is the primary client class and is used to manage account-wide metadata or databases. |
CosmosDatabase |
This class represents a database within the account. |
CosmosContainer |
This class is primarily used to perform read, update, and delete operations on either the container or the items stored within the container. |
PartitionKey |
This class represents a logical partition key. This class is required for many common operations and queries. |
The sample code in the template uses a database named cosmicworks
and container named products
. The products
container contains details such as name, category, quantity, a unique identifier, and a sale flag for each product. The container uses the /category
property as a logical partition key.
This sample creates a new instance of CosmosClient
using azcosmos.NewClient
and authenticates using a DefaultAzureCredential
instance.
credential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
return err
}
clientOptions := azcosmos.ClientOptions{
EnableContentResponseOnWrite: true,
}
client, err := azcosmos.NewClient("<azure-cosmos-db-nosql-account-endpoint>", credential, &clientOptions)
if err != nil {
return err
}
Use client.NewDatabase
to retrieve the existing database named cosmicworks
.
database, err := client.NewDatabase("cosmicworks")
if err != nil {
return err
}
Retrieve the existing products
container using database.NewContainer
.
container, err := database.NewContainer("products")
if err != nil {
return err
}
Build a Go type with all of the members you want to serialize into JSON. In this example, the type has a unique identifier, and fields for category, name, quantity, price, and sale.
type Item struct {
Id string `json:"id"`
Category string `json:"category"`
Name string `json:"name"`
Quantity int `json:"quantity"`
Price float32 `json:"price"`
Clearance bool `json:"clearance"`
}
Create an item in the container using container.UpsertItem
. This method "upserts" the item effectively replacing the item if it already exists.
item := Item {
Id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
Category: "gear-surf-surfboards",
Name: "Yamba Surfboard",
Quantity: 12,
Price: 850.00,
Clearance: false,
}
partitionKey := azcosmos.NewPartitionKeyString("gear-surf-surfboards")
context := context.TODO()
bytes, err := json.Marshal(item)
if err != nil {
return err
}
response, err := container.UpsertItem(context, partitionKey, bytes, nil)
if err != nil {
return err
}
Perform a point read operation by using both the unique identifier (id
) and partition key fields. Use container.ReadItem
to efficiently retrieve the specific item.
partitionKey := azcosmos.NewPartitionKeyString("gear-surf-surfboards")
context := context.TODO()
itemId := "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"
response, err := container.ReadItem(context, partitionKey, itemId, nil)
if err != nil {
return err
}
if response.RawResponse.StatusCode == 200 {
read_item := Item{}
err := json.Unmarshal(response.Value, &read_item)
if err != nil {
return err
}
}
Perform a query over multiple items in a container using container.NewQueryItemsPager
. Find all items within a specified category using this parameterized query:
SELECT * FROM products p WHERE p.category = @category
partitionKey := azcosmos.NewPartitionKeyString("gear-surf-surfboards")
query := "SELECT * FROM products p WHERE p.category = @category"
queryOptions := azcosmos.QueryOptions{
QueryParameters: []azcosmos.QueryParameter{
{Name: "@category", Value: "gear-surf-surfboards"},
},
}
pager := container.NewQueryItemsPager(query, partitionKey, &queryOptions)
Parse the paginated results of the query by looping through each page of results using pager.NextPage
. Use pager.More
to determine if there are any results left at the start of each loop.
items := []Item{}
for pager.More() {
response, err := pager.NextPage(context.TODO())
if err != nil {
return err
}
for _, bytes := range response.Items {
item := Item{}
err := json.Unmarshal(bytes, &item)
if err != nil {
return err
}
items = append(items, item)
}
}
Use the Visual Studio Code extension for Azure Cosmos DB to explore your NoSQL data. You can perform core database operations including, but not limited to:
For more information, see How-to use Visual Studio Code extension to explore Azure Cosmos DB for NoSQL data.
When you no longer need the sample application or resources, remove the corresponding deployment and all resources.
azd down
Događaj
Izgradite inteligentne aplikacije
17. mar 21 - 21. mar 10
Pridružite se seriji sastanaka kako biste izgradili skalabilna AI rešenja zasnovana na stvarnim slučajevima korišćenja sa kolegama programerima i stručnjacima.
Registrujte se odmahObuka
Putanja učenja
Get started with Azure Cosmos DB for NoSQL - Training
Get started with Azure Cosmos DB for NoSQL
Certifikacija
Microsoft Certified: Azure Cosmos DB Developer Specialty - Certifications
Write efficient queries, create indexing policies, manage, and provision resources in the SQL API and SDK with Microsoft Azure Cosmos DB.
Dokumentacija
API for NoSQL Go examples for Azure Cosmos DB
Find Go examples on GitHub for common tasks in Azure Cosmos DB, including CRUD operations.
Azure Cosmos DB: SQL Go, SDK & resources
Learn all about the API for NoSQL and Go SDK including release dates, retirement dates, and changes made between each version of the Azure Cosmos DB Go SDK.
Quickstart - Azure SDK for Node.js - Azure Cosmos DB for NoSQL
Deploy a Node.js Express web application that uses the Azure SDK for Node.js to interact with Azure Cosmos DB for NoSQL data in this quickstart.