Редактиране

Споделяне чрез


Quickstart: Use Azure Cosmos DB for Table with Azure SDK for Node.js

In this quickstart, you deploy a basic Azure Cosmos DB for Table application using the Azure SDK for Node.js. Azure Cosmos DB for Table is a schemaless data store allowing applications to store structured table data in the cloud. You learn how to create tables, rows, and perform basic tasks within your Azure Cosmos DB resource using the Azure SDK for Node.js.

API reference documentation | Library source code | Package (npm) | Azure Developer CLI

Prerequisites

  • Azure Developer CLI
  • Docker Desktop
  • Node.js 22 or newer

If you don't have an Azure account, create a free account before you begin.

Initialize the project

Use the Azure Developer CLI (azd) to create an Azure Cosmos DB for Table account and deploy a containerized sample application. The sample application uses the client library to manage, create, read, and query sample data.

  1. Open a terminal in an empty directory.

  2. 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
    
  3. Use azd init to initialize the project.

    azd init --template cosmos-db-table-nodejs-quickstart
    
  4. During initialization, configure a unique environment name.

  5. Deploy the Azure Cosmos DB account using azd up. The Bicep templates also deploy a sample web application.

    azd up
    
  6. 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.

  7. 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.
    
  8. Use the URL in the console to navigate to your web application in the browser. Observe the output of the running app.

Screenshot of the running web application.

Screenshot of the running web application.

Install the client library

The client library is available through npm, as the @azure/data-tables package.

  1. Open a terminal and navigate to the /src/ts folder.

    cd ./src/ts
    
  2. If not already installed, install the @azure/data-tables package using npm install.

    npm install --save @azure/data-tables
    
  3. Open and review the src/ts/package.json file to validate that the @azure/data-tables entry exists.

  1. Open a terminal and navigate to the /src/js folder.

    cd ./src/js
    
  2. If not already installed, install the @azure/data-tables package using npm install.

    npm install --save @azure/data-tables
    
  3. Open and review the src/js/package.json file to validate that the @azure/data-tables entry exists.

Object model

Name Description
TableServiceClient This type is the primary client type and is used to manage account-wide metadata or databases.
TableClient This type represents the client for a table within the account.

Code examples

The sample code in the template uses a table named cosmicworks-products. The cosmicworks-products table contains details such as name, category, quantity, price, a unique identifier, and a sale flag for each product. The container uses a unique identifier as the row key and category as a partition key.

Authenticate the client

This sample creates a new instance of the TableServiceClient type.

let client: TableServiceClient = new TableServiceClient("<azure-cosmos-db-table-account-endpoint>", "<credential>");
const credential = new DefaultAzureCredential();

let client = new TableServiceClient("<azure-cosmos-db-table-account-endpoint>", credential);

Get a table

This sample creates an instance of the TableClient type using the GetTableClient function of the TableServiceClient type.

let table: TableClient = new TableClient("<azure-cosmos-db-table-account-endpoint>", "<azure-cosmos-db-table-name>", credential);
let table = new TableClient("<azure-cosmos-db-table-account-endpoint>", "<azure-cosmos-db-table-name>", credential);

Create an entity

The easiest way to create a new entity in a table is to derive a new interface from TableEntity and then create a new object of that type.

export interface Product extends TableEntity {
    name: string;
    quantity: number;
    price: number;
    clearance: boolean;
}
const entity: Product = {
    rowKey: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
    partitionKey: 'gear-surf-surfboards',
    name: 'Yamba Surfboard',
    quantity: 12,
    price: 850.00,
    clearance: false
};

The easiest way to create a new item in a table is to build a JSON object.

const entity = {
    rowKey: 'aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb',
    partitionKey: 'gear-surf-surfboards',
    name: 'Yamba Surfboard',
    quantity: 12,
    price: 850.00,
    clearance: false
};

Create an entity in the table using the upsertEntity method from the TableService instance.

await table.upsertEntity<Product>(entity, "Replace"); 
await table.upsertEntity(entity, "Replace");

Get an entity

You can retrieve a specific entity from a table using the getEntity method, the row key for the entity, and partition key of the entity.

const response: GetTableEntityResponse<TableEntityResult<Product>> = await table.getEntity<Product>(partitionKey, rowKey);

const entity: Product = response as Product;
const entity = await table.getEntity(partitionKey, rowKey);

Query entities

After you insert an entity, you can also run a query to get all entities that match a specific filter by using listEntities with an OData filter.

const partitionKey: string = 'gear-surf-surfboards';

const filter: string = `PartitionKey eq '${partitionKey}'`

const queryOptions: TableEntityQueryOptions = { filter: filter }

const entities: PagedAsyncIterableIterator<TableEntityResult<Product>, TableEntityResultPage<Product>> = table.listEntities<Product>({ queryOptions: queryOptions });
const partitionKey = 'gear-surf-surfboards';

const entities = table.listEntities({
    queryOptions: {
        filter: `PartitionKey eq '${partitionKey}'`
    }
});

Parse the paginated results of the query by using an asynchronous for await loop on the paginated set of entities.

for await(const entity of entities) {
    // Do something
}
for await(const entity of entities) {
    // Do something
}

Clean up resources

When you no longer need the sample application or resources, remove the corresponding deployment and all resources.

azd down