Übung: Hinzufügen von JavaScript-Code für die Verwendung mit Cosmos DB

Abgeschlossen

In dieser Lerneinheit werden Sie Skripts erstellen und ausführen, die SQL-Schlüsselwörter wie LIKE, JOIN und WHERE nutzen, um Daten mit dem Cosmos SDK zu finden.

Erstellen des Skripts zum Suchen von Produkten im Container

  1. Wählen Sie in Visual Studio Code im Menü Datei die Option Neue Textdatei aus.

  2. Klicken Sie im Menü Datei auf Speichern unter. Speichern Sie die neue Datei unter dem Namen 2-contoso-products-find.js.

  3. Kopieren Sie den folgenden JavaScript-Code in diese Datei:

    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");
    }
    
  4. Führen Sie die JavaScript-Datei im Visual Studio Code-Terminal aus, um alle Fahrräder zu finden:

    node 2-contoso-products-find.js find categoryName '%Bikes%'
    

    Der bikes-Ausdruck wird von Prozentzeichen (%) umschlossen, um auch teilweise Übereinstimmungen zuzulassen.

    Die SQL-Abfrage in der executeSqlFind-Methode für den Container verwendet das Schlüsselwort LIKE und Abfrageparameter, um alle Elemente mit einem categoryName zu finden, der Bikes enthält.

  5. Führen Sie eine weitere Abfrage aus, um alle Produkte mit dem Wort Blue im Namen zu finden.

    node 2-contoso-products-find.js find name '%Blue%'
    
  6. Führen Sie eine weitere Abfrage aus, um den Produktbestand für Fahrräder in Seattle zu ermitteln.

    node 2-contoso-products-find.js find-inventory categoryName '%Bikes%' Seattle
    
  7. Führen Sie eine weitere Abfrage aus, um alle Produkte mit dem Wort Blue im Namen am Standort Dallas zu finden.

    node 2-contoso-products-find.js find-inventory name '%Blue%' Dallas
    

Erstellen des Skripts zum Ausführen eines Upsert-Vorgangs für Produkte in einem Container

  1. Wählen Sie in Visual Studio Code im Menü Datei die Option Neue Textdatei aus.

  2. Klicken Sie im Menü Datei auf Speichern unter. Speichern Sie die neue Datei unter dem Namen 3-contoso-products-upsert.js.

  3. Kopieren Sie den folgenden JavaScript-Code in diese Datei:

    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);
    
  4. Erstellen Sie eine neue Datei für das Produkt (3-contoso-products-upsert-insert.json), und fügen Sie das folgende JSON-Objekt ein.

    {
        "id": "123",
        "categoryName": "xyz",
        "name": "_a new item inserted"
    }
    

    Beachten Sie, dass es für dieses Objekt mit der ID 123 keinen Bestand gibt.

  5. Erstellen Sie eine neue Datei für das Produkt (3-contoso-products-upsert-update.json), und fügen Sie das folgende JSON-Objekt ein.

    {
      "id": "123",
      "categoryName": "xyz",
      "name": "_a new item updated",
      "inventory": [
        {
          "location": "Dallas",
          "inventory": 100
        }
      ]
    }
    

    Beachten Sie, dass für dieses Objekt Bestand vorhanden ist.

  6. Führen Sie die JavaScript-Datei im Visual Studio Code-Terminal aus, um einen Upsert für das neue Produkt auszuführen.

    3-contoso-products-upsert.js
    

    Da kein Produkt mit der ID vorhanden ist, wird es eingefügt. Anschließend aktualisiert das Skript das Produkt mit einem Bestand. Sowohl beim Einfügen als auch beim Aktualisieren wird derselbe Upsert-Code verwendet.