有没有更简单的方法将 javascript 对象转换为 dynamodb 更新表达式?

Is there an easier way to convert javascript object to dynamodb update expression?

我正在使用 nodejs aws-sdk/clients/dynamodb 库和 dynamodb。我需要更新 table 中的一个项目。以下是更新项目的示例代码:

params = {
    TableName:table,
    Key:{
        "year": year,
        "title": title
    },
    UpdateExpression: "set info.rating = info.rating + :val",
    ExpressionAttributeValues:{
        ":val": 1
    },
    ReturnValues:"UPDATED_NEW"
};

我将不得不在 UpdateExpression 中指定 info 中的每个属性。我的 info 对象非常大,我正在寻找一种更简单的方法来做到这一点。是否有内置方法支持将对象更新为 dynamodb 项目?类似于:

params = {
    TableName:table,
    Key:{
        "year": year,
        "title": title
    },
    Item: info
};

您可以使用文档客户端:

Version 2.2.0 of the AWS SDK for JavaScript introduces support for the document client abstraction in the AWS.DynamoDB namespace. The document client abstraction makes it easier to read and write data to Amazon DynamoDB with the AWS SDK for JavaScript. Now you can use native JavaScript objects without annotating them as AttributeValue types.

例如:

var docClient = new AWS.DynamoDB.DocumentClient({region: 'us-west-2'});

var params = {
    Item: {
        hashkey: 'key',
        boolAttr: true,
        listAttr: [1, 'baz', true]
        mapAttr: {
            foo: 'bar'
        }
    },
    TableName: 'table'
};

docClient.put(params, function(err, data){
    if (err) console.log(err);
    else console.log(data);
});

https://aws.amazon.com/blogs/developer/announcing-the-amazon-dynamodb-document-client-in-the-aws-sdk-for-javascript/

E.J给出的答案。 Brennan 非常适合替换 整个项目的情况。 DocumentClient 简化了处理 DynamoDB 属性类型的麻烦,但给出的示例使用 put 方法。根据文档 put 传递到 putItem which

Creates a new item, or replaces an old item with a new item

这意味着它不会帮助您对现有项目进行部分更新,因为您还没有完整的记录(并且可以完全替换)。对于部分更新,您必须使用 updateItem,或者它的 DocumentClient 对应物,update.

AWS 实验室有 published a utility 来帮助构建更新表达式以与 updateItem 一起使用。由于我通常更喜欢使用 DocumentClient,因此我使用 DynamoDB 的 Converter 提供的实用函数解组值(是的,我知道这有点来回,但它使测试更容易)。

const AWS = require('aws-sdk');
const db = new AWS.DynamoDB.DocumentClient();
const { UpdateExpression, ExpressionAttributes } = require('@aws/dynamodb-expressions');
const { unmarshall } = AWS.DynamoDB.Converter;

const updateExpressionProps = ({ category, classification }) => {
  attributes = new ExpressionAttributes();
  expression = new UpdateExpression();

  expression.set('category', category);
  expression.set('classification', classification);

  return {
    UpdateExpression: expression.serialize(attributes),
    ExpressionAttributeNames: attributes.names,
    ExpressionAttributeValues: unmarshall(attributes.values),
  };
};

const updateRequest = async ({ id, subject, category, classification }) =>
  await db
    .update({
      TableName: 'table-name',
      Key: {
        id,
        subject,
      },
      ...updateExpressionProps({ category, classification }),
    })
    .promise();

这段代码 更新用 idsubject 标识的记录上的 categoryclassification 属性无需手动构建正确的 UpdateExpression 字符串。这个例子可以很容易地推广到整个项目中可重用的东西。