skip to Main Content

I have a container of cost guides in my Azure Cosmos DB (using the core SQL API). Each cost guide has an array of materials. I need to add a material to this array in every document in the container. Is this possible with javascript in a single transaction? I am familiar with partially updating documents individually using the patch operation but I would prefer to do it all at once if possible. I’m using the @azure/cosmos version 3.15 package

This is how I update individual documents in my function app:

const CosmosClient = require('@azure/cosmos').CosmosClient;
const config = require('../config/config');
const { endpoint, key, databaseId } = config;
const client = new CosmosClient({ endpoint, key });
const database = client.database(databaseId);

module.exports = async function (context, req) {
    const containerId = req.query.containerId;
    const container = database.container(containerId);
    const id = req.query.id;
    const updates = req.body;

    const querySpec = {
        query: `SELECT * from c where c.id = "${id}"`
    }

    const { resources: items } = await container.items
        .query(querySpec)
        .fetchAll()

    const patchOp = [];

    // loop through updates object
    Object.keys(updates).map(key => {
        patchOp.push({
            op: 'replace',
            path: `/${key}`,
            value: updates[key]
        })
    })

    const { resource: patchSource } = await container.item(items[0].id, items[0].id).patch(patchOp);
}

2

Answers


  1. Technically, till now no such type of single transaction using Java Script is available. There are other possibilities like using .NET which are used for similar requirements.

    Other languages like JAVA and PYTHON are having partial implementation. Terraform can also help a bit in partial implementation.

    https://learn.microsoft.com/en-us/azure/cosmos-db/sql/sql-api-sdk-bulk-executor-dot-net

    Login or Signup to reply.
  2. The closest I have seen is using the bulk or batch operation on items within a container. For example:

    const operations = [
       {
          operationType: "Create",
          resourceBody: { id: "doc1", name: "sample", key: "A" }
       },
       {
          operationType: "Upsert",
          partitionKey: 'A',
          resourceBody: { id: "doc2", name: "other", key: "A" }
       }
    ];
    
    await database.container.items.batch(operations);
    

    Link to azure documentation: https://learn.microsoft.com/en-us/javascript/api/@azure/cosmos/items?view=azure-node-latest#@azure-cosmos-items-batch

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search