练习 - 添加 JavaScript 代码以使用 Cosmos DB
在本单元中,你将创建并运行脚本,这些脚本使用 SQL 关键字(如 LIKE、JOIN 和 WHERE)通过 Cosmos SDK 查找数据。
创建脚本以在容器中查找产品
在 Visual Studio Code 的“文件”菜单中,选择“新建文本文件”。
在“文件”菜单中,选择“另存为”。 使用名称 2-contoso-products-find.js 保存新文件。
复制以下 JavaScript 并将其粘贴到该文件中:
import * as path from "path"; import { promises as fs } from "fs"; import { fileURLToPath } from "url"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); // Get environment variables from .env import * as dotenv from "dotenv"; dotenv.config(); // Get Cosmos Client import { CosmosClient } from "@azure/cosmos"; // Provide required connection from environment variables const cosmosSecret = process.env.COSMOS_CONNECTION_STRING; // Authenticate to Azure Cosmos DB const cosmosClient = new CosmosClient(cosmosSecret); // Set Database name and container name const databaseName = process.env.COSMOS_DATABASE_NAME; const containerName = process.env.COSMOS_CONTAINER_NAME; // Get Container const container = await cosmosClient .database(databaseName) .container(containerName); // Find all products that match a property with a value like `value` async function executeSqlFind(property, value) { // Build query const querySpec = { query: `select * from products p where p.${property} LIKE @propertyValue`, parameters: [ { name: "@propertyValue", value: `${value}`, }, ], }; // Show query console.log(querySpec); // Get results const { resources } = await container.items.query(querySpec).fetchAll(); let i = 0; // Show results of query for (const item of resources) { console.log(`${++i}: ${item.id}: ${item.name}, ${item.sku}`); } } // Find inventory of products with property/value and location async function executeSqlInventory(propertyName, propertyValue, locationPropertyName, locationPropertyValue) { // Build query const querySpec = { query: `select p.id, p.name, i.location, i.inventory from products p JOIN i IN p.inventory where p.${propertyName} LIKE @propertyValue AND i.${locationPropertyName}=@locationPropertyValue`, parameters: [ { name: "@propertyValue", value: `${propertyValue}`, }, { name: "@locationPropertyValue", value: `${locationPropertyValue}` }, ], }; // Show query console.log(querySpec); // Get results const { resources } = await container.items.query(querySpec).fetchAll(); let i = 0; // Show results of query console.log(`Looking for ${propertyName}=${propertyValue}, ${locationPropertyName}=${locationPropertyValue}`); for (const item of resources) { console.log( `${++i}: ${item.id}: '${item.name}': current inventory = ${ item.inventory }` ); } } // Example queries /* // find all bikes based on partial match to property value node 2-contoso-products-find.js find categoryName '%Bikes%' node 2-contoso-products-find.js find name '%Blue%' // find inventory at location on partial match to property value and specific location node 2-contoso-products-find.js find-inventory categoryName '%Bikes%' location Seattle node 2-contoso-products-find.js find-inventory name '%Blue%' location Dallas */ const args = process.argv; if (args && args[2] == "find") { await executeSqlFind(args[3], args[4]); } else if (args && args[2] == "find-inventory") { await executeSqlInventory(args[3], args[4], args[5], args[6]); } else { console.log("products: no args used"); }
在 Visual Studio Code 终端中,执行 JavaScript 文件以查找所有自行车:
node 2-contoso-products-find.js find categoryName '%Bikes%'
术语
bikes
用百分比符号%
包住,表示部分匹配。容器的
executeSqlFind
方法中的 SQL 查询使用 LIKE 关键字和查询参数查找 categoryName 包含Bikes
的任何项。运行另一个查询以查找名称中包含
Blue
一词的所有产品。node 2-contoso-products-find.js find name '%Blue%'
运行另一个查询以查找西雅图的自行车产品库存。
node 2-contoso-products-find.js find-inventory categoryName '%Bikes%' Seattle
运行另一个查询以查找达拉斯的名称中包含
Blue
一词的所有产品库存。node 2-contoso-products-find.js find-inventory name '%Blue%' Dallas
创建脚本以将产品更新插入到容器
在 Visual Studio Code 的“文件”菜单中,选择“新建文本文件”。
在“文件”菜单中,选择“另存为”。 使用名称 3-contoso-products-upsert.js 保存新文件。
复制以下 JavaScript 并将其粘贴到该文件中:
import * as path from "path"; import { promises as fs } from "fs"; import { fileURLToPath } from "url"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); // Get environment variables from .env import * as dotenv from "dotenv"; dotenv.config(); // Get Cosmos Client import { CosmosClient } from "@azure/cosmos"; // Provide required connection from environment variables const cosmosSecret = process.env.COSMOS_CONNECTION_STRING; // Authenticate to Azure Cosmos DB const cosmosClient = new CosmosClient(cosmosSecret); // Set Database name and container name const databaseName = process.env.COSMOS_DATABASE_NAME; const containerName = process.env.COSMOS_CONTAINER_NAME; // Get Container const container = await cosmosClient.database(databaseName).container(containerName); // Either insert or update item async function upsert(fileAndPathToJson, encoding='utf-8') { // Get item from file const data = JSON.parse(await fs.readFile(path.join(__dirname, fileAndPathToJson), encoding)); // Process request // result.resource is the returned item const result = await container.items.upsert(data); if(result.statusCode===201){ console.log("Inserted data"); } else if (result.statusCode===200){ console.log("Updated data"); } else { console.log(`unexpected statusCode ${result.statusCode}`); } } // Insert data - statusCode = 201 await upsert('./3-contoso-products-upsert-insert.json'); // Update data - statusCode = 200 await upsert('./3-contoso-products-upsert-update.json'); // Get item from container and partition key const { resource } = await container.item("123", "xyz").read(); // Show final item console.log(resource);
为产品 3-contoso-products-upsert-insert.json 创建新文件,并粘贴以下 JSON 对象。
{ "id": "123", "categoryName": "xyz", "name": "_a new item inserted" }
请注意,ID 为
123
的此对象没有任何库存。为产品 3-contoso-products-upsert-update.json 创建新文件,并粘贴以下 JSON 对象。
{ "id": "123", "categoryName": "xyz", "name": "_a new item updated", "inventory": [ { "location": "Dallas", "inventory": 100 } ] }
请注意,此对象确实有库存。
在 Visual Studio Code 终端中,执行 JavaScript 文件以更新插入新产品。
3-contoso-products-upsert.js
由于具有该 ID 的产品不存在,因此会插入。 然后脚本将使用库存更新产品。 插入和更新功能都使用相同的代码来更新插入。