从 CosmosDB 中删除项目

问题描述 投票:0回答:1

我正在尝试从 Azure CosmosDB 中删除条目。

文档说:

/**
 * Delete item
 * Pass the id and partition key value to delete the item
 */
const { resource: result } = await container.item(id, category).delete();
console.log(`Deleted item with id: ${id}`);

我删除和项目的功能是:

// takes in an entry id to detete and deletes it with the documentation
async function findItemsToDelete(idToDelete){

    const category = config.partitionKey; // partitionKey is {kind: "Hash", paths: ["/requests"]} and I've also tried just "/requests"

    // the four lines below are correct
    const { endpoint, key, databaseId, containerId } = config;
    const client = new CosmosClient({ endpoint, key });
    const database = client.database(databaseId);
    const container = database.container(containerId);

     // query to return item with id (random code to make sure the item exists)- not important
     const querySpec = {
         query: `SELECT * FROM c WHERE c.id = "${idToDelete}"`
     };
     const { resources: items } = await container.items
         .query(querySpec)
         .fetchAll();

// below is the delete code from the documentation
    const { resource: result } = await container.item(idToDelete, category).delete();
    
    // random array holding the item that was just deleted- not important
    return items;
  }

当我尝试调用此方法时,收到一条错误消息:系统中不存在具有指定 ID 的实体。有谁知道如何正确实施这一点?我知道 id 是正确的,但我相信我可能在partitionKey/Category 部分做错了什么。

我在这篇文章中看到:无法从 CosmosDB 中删除项目 我可能需要分区键值,但我不知道那是什么或如何获取它。如果您知道发生了什么事,请告诉我!

javascript azure azure-cosmosdb azure-cosmosdb-sqlapi
1个回答
0
投票

这里是使用批量删除方法删除所有满足条件的文档的示例代码

cosmosClient 是在方法之外准备的,因为我们在其他方法中重用相同的客户端。

每次批量删除的有效负载应小于 2MB,且少于 100 条记录。为了安全起见,我保留 50 作为块大小。

const bulkDelete = async (id,tableName,cosmosClient) => {
const chunkSize=50; // 2MB or less than 100 items per batch
const container = cosmosClient.container(tableName);
try {
  const querySpec = {
    query:
      "SELECT * FROM c WHERE c.id = @id",
    parameters: [
      { name: "@id", value: id },
    ],
  };

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

  for (let i = 0; i < items.length; i += chunkSize) {

    const chunk = items.slice(i, i + chunkSize);
    await container.items.bulk(chunk.map(item => ({
        operationType: "Delete",
        partitionKey: item.dashboardId, //partition key of the item
        id: item.id //actual id of the item
    })));
  
  }

} catch (error) {
  console.error("FAIL: Error deleting item from Cosmos DB - " + error);
  throw error;
}};
© www.soinside.com 2019 - 2024. All rights reserved.