javascript 调用TransactWriteItems或BatchWriteItems API时未先调用GET项

koaltpgm  于 2023-02-28  发布在  Java
关注(0)|答案(1)|浏览(140)

我想更新DynamoDB表中的项目。我只想更新每个项目中的2个属性。如果项目不存在,我想忽略它。我尝试了TransactWriteItems或BatchWriteItems API,但使用它们时,我必须首先调用getItems API以筛选出不存在的项目。是否有办法避免调用getItems API调用?
index.js

const {DocumentClient} = require("aws-sdk/clients/dynamodb");
const documentClient = new DocumentClient({region:'us-west-2'});
exports.handler = async (event, context) => {
  const filteredItems = await client.getItems(event.body.items)
  await client.updateItems(filteredItems, event.body.soldPrice, documentClient);
}

client.js

const updateItems = async(filteredItems, soldPrice, documentClient) => {
   let params = {
      RequestItems: {
        [tableName] : {
           filteredItems.map((key) =>({
              PutRequest: {
                Item: {
                  itemNumber: key.itemNumber,
                  soldPrice: soldPrice,
                  lastModified: new Date().toISOString()
                }
              }
           })
        }
   };
   documentClient.batchWrite(params).promise()
}

更新:我也尝试了以下,这清除了现有的值:

const buildUpdateRequest = (filteredItems, soldPrice) => {
  return items.map((item) => ({
    PutRequest: {
        Item: {
            'itemNumber': item,
            'soldPrice': soldPrice,
            'lastModified': new Date().toISOString()
        },
        ConditionExpression: 'attribute_exists(itemNumber)'
    }
  }));
}
const batchWriteInvoices = (filteredItems, state, documentClient) => {
  const params = {
    RequestItems: {
        [tableName]: buildUpdateRequest(filteredItems, state),
    }
  };

  documentClient.batchWrite(params, (err, data) => {
    if (err) {
        console.error('Error:', err);
    } else {
        console.log('Success:', data);
    }
  });
}
myzjeezk

myzjeezk1#

您需要使用ConditionExpression
在cli中,对于PutItem,它看起来像下面这样。相同的逻辑适用于您的BatchWrite或TxWrite。

aws dynamodb put-item \
    --table-name ProductCatalog \
    --item file://item.json \
    --condition-expression "attribute_exists(Id)"

相关问题