如何部分更新DynamoDB表?

时间:2017-10-17 23:10:31

标签: javascript database rest nosql amazon-dynamodb

我们在DynamoDB中进行部分更新时遇到了很多麻烦。

尝试使用聚合而不是实体来使用NoSQL中的最佳实践,因此我们的数据看起来有点像这样:

[
{
    "userLogin": {
        "ipAddress": "123.222.121.1234",
        "lastLogin": "2017-10-16T17:38:59.818Z",
        "userAgent": "bob",
        "geoLocation": "lat-121 long-312"
    },
    "addresses": {
        "billingAddress": {
            "streetName": "york street",
            "province": "ontario",
            "city": "toronto",
            "streetNumber": "18",
            "postalCode": "m5a2v7"
        },
        "businessAddress": {
            "streetName": "york street",
            "province": "ontario",
            "city": "toronto",
            "streetNumber": "18",
            "postalCode": "m5a2v7"
        },
        "mailingAddress": {
            "streetName": "york street",
            "province": "ontario",
            "city": "toronto",
            "streetNumber": "18",
            "postalCode": "m5a2v7"
        },
    },
    "paymentTransaction": {
        "orderId": 5,
        "amount": 75,
        "transactionTimestamp": "2017-10-16T17:38:59.818Z"
    },
    "userId": "00uc4sxyi7gfQoFum0h7",
    "phoneNumbers": {
        "workNumber": "647-123-1234",
        "homeNumber": "647-321-4321"
    },
    "userProfile": {
        "role": "admin",
        "verifiedTimeStamp": "2017-10-16T17:38:59.818Z",
        "termsConditionTimeStamp": "2017-10-16T17:38:59.818Z",
        "verified": "TRUE",
        "createdTimeStamp": "2017-10-16T17:38:59.818Z",
        "termsConditionVersion": "1.0",
        "email": "kyle.truong@test.io"
    }
}

我们要做的就是向这样的身体提出请求:

PUT /api/user-profiles/00uc4sxyi7gfQoFum0h7
body: {
    "userLogin": { "lastLogin": "2017-12-16T17:38:59.818Z" }
}

并让它更新User表中的一个属性。

updateItem API似乎需要在更新之前定义要更新的属性,但我们希望它基于请求的主体更加灵活和动态。

这个帖子似乎说不可能:

How to update multiple items in a DynamoDB table at once

如果是这样,在DynamoDB中只更新项目中的部分属性对象的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

如果您的userLogin是地图类型,则在dynamoDB中,您可以更新lastLoginkey的值。在Java下面的代码可能有所帮助。这里的列名是userLogin,newKey是lastLogin。可以找到完整的代码段here

UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey(primaryKey,primaryKeyValue).withReturnValues(ReturnValue.ALL_NEW).
        withUpdateExpression("set #columnName." + newKey + " = :columnValue").
        withNameMap(new NameMap().with("#columnName", updateColumn)).
        withValueMap(new ValueMap().with(":columnValue", newValue)).withConditionExpression("attribute_exists("+ updateColumn +")");

table.updateItem(updateItemSpec);