

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# UpdateItem


`UpdateItem`请求映射文档允许您告诉 D Amazon AppSync ynamoDB 解析器向 DynamoDB 发出`UpdateItem`请求，并允许您指定以下内容：
+ DynamoDB 中的项目的键
+ 描述如何更新 DynamoDB 中的项目的更新表达式
+ 操作成功执行的条件

`UpdateItem` 映射文档具有以下结构：

```
{
    "version" : "2018-05-29",
    "operation" : "UpdateItem",
    "customPartitionKey" : "foo",
    "populateIndexFields" : boolean value,
    "key": {
        "foo" : ... typed value,
        "bar" : ... typed value
    },
    "update" : {
        "expression" : "someExpression",
        "expressionNames" : {
           "#foo" : "foo"
       },
       "expressionValues" : {
           ":bar" : ... typed value
       }
    },
    "condition" : {
        ...
    },
    "_version" : 1
}
```

字段定义如下：

## UpdateItem 字段


### UpdateItem 字段列表


 **`version`**   
模板定义版本。目前支持 `2017-02-28` 和 `2018-05-29`。该值为必填项。

 **`operation`**   
要执行的 DynamoDB 操作。要执行 `UpdateItem` DynamoDB 操作，该字段必须设置为 `UpdateItem`。该值为必填项。

 **`key`**   
DynamoDB 中的项目的键。DynamoDB 项目可能具有单个哈希键，也可能具有哈希键和排序键，具体取决于表结构。有关指定“类型化值”的更多信息，请参阅[类型系统（请求映射）](aws-appsync-resolver-mapping-template-reference-dynamodb-typed-values-request.md)。该值为必填项。

 **`update`**   
`update` 部分用于指定一个更新表达式，以描述如何更新 DynamoDB 中的项目。有关如何编写更新表达式的更多信息，请参阅 [DynamoDB 文档 UpdateExpressions ](https://docs.amazonaws.cn/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html)。此部分是必需的。  
`update` 部分有三个组成部分：    
** `expression` **  
更新表达式。该值为必填项。  
** `expressionNames` **  
以键值对形式替换表达式属性*名称* 占位符。键对应于 `expression` 中使用的名称占位符，值必须是与 DynamoDB 中的项目的属性名称对应的字符串。该字段是可选的，只应填充 `expression` 中使用的表达式属性名称占位符的替换内容。  
** `expressionValues` **  
以键值对形式替换表达式属性*值* 占位符。键对应于 `expression` 中使用的值占位符，而值必须为类型化值。有关如何指定“类型化值”的更多信息，请参阅[类型系统（请求映射）](aws-appsync-resolver-mapping-template-reference-dynamodb-typed-values-request.md)。必须指定此值。该字段是可选的，只应填充 `expression` 中使用的表达式属性值占位符的替换内容。

 **`condition`**   
根据 DynamoDB 中已有的对象状态，确定请求是否应成功的条件。如果未指定条件，则 `UpdateItem` 请求将更新现有条目，而不考虑其当前状态。有关条件的更多信息，请参阅[条件表达式](aws-appsync-resolver-mapping-template-reference-dynamodb-condition-expressions.md)。该值为可选项。

 **`_version`**   
表示项目的最新已知版本的数值。该值为可选项。该字段用于*冲突检测*，仅受版本控制的数据来源支持。

**`customPartitionKey`**  
启用后，此字符串值将修改启用版本控制后增量同步表使用的`ds_sk`和`ds_pk`记录的格式（有关更多信息，请参阅*《Amazon AppSync 开发人员指南》*中的[冲突检测和同步](https://docs.amazonaws.cn/appsync/latest/devguide/conflict-detection-and-sync.html)）。如果启用，还会启用 `populateIndexFields` 条目处理。该字段是可选的。

**`populateIndexFields`**  
一个布尔值，在**与 `customPartitionKey` 一起**启用时，它为增量同步表中的每个记录创建新条目，具体来说是在 `gsi_ds_pk` 和 `gsi_ds_sk` 列中创建新条目。有关更多信息，请参阅《Amazon AppSync 开发人员指南》中的[冲突检测和同步](https://docs.amazonaws.cn/appsync/latest/devguide/conflict-detection-and-sync.html)。**该字段是可选的。

在 DynamoDB 中更新的项目将自动转换为 GraphQL 和 JSON 基元类型，并且可以在映射上下文 (`$context.result`) 中使用。

有关 DynamoDB 类型转换的更多信息，请参阅[类型系统（响应映射）](aws-appsync-resolver-mapping-template-reference-dynamodb-typed-values-responses.md)。

有关响应映射模板的更多信息，请参阅[解析器映射模板概述](resolver-mapping-template-reference-overview.md#aws-appsync-resolver-mapping-template-reference-overview)。

## 示例 1


以下示例是 GraphQL 变更 `upvote(id: ID!)` 的映射模板。

在该示例中，DynamoDB 中的项目的 `upvotes` 和 `version` 字段递增 1。

```
{
    "version" : "2017-02-28",
    "operation" : "UpdateItem",
    "key" : {
        "id" : $util.dynamodb.toDynamoDBJson($ctx.args.id)
    },
    "update" : {
        "expression" : "ADD #votefield :plusOne, version :plusOne",
        "expressionNames" : {
            "#votefield" : "upvotes"
        },
        "expressionValues" : {
            ":plusOne" : { "N" : 1 }
        }
    }
}
```

## 示例 2


以下示例是 GraphQL 变更 `updateItem(id: ID!, title: String, author: String, expectedVersion: Int!)` 的映射模板。

这是一个复杂的示例，用于检查参数并动态生成更新表达式，此表达式仅包含由客户端提供的参数。例如，如果省略了 `title` 和 `author`，则不会更新它们。如果指定了一个参数，但该参数的值为 `null`，则会从 DynamoDB 上的对象中删除该字段。最后，该操作具有一个条件，用于验证目前位于 DynamoDB 中的项目的 `version` 字段是否设置为 `expectedVersion`：

```
{
    "version" : "2017-02-28",

    "operation" : "UpdateItem",

    "key" : {
        "id" : $util.dynamodb.toDynamoDBJson($ctx.args.id)
    },

    ## Set up some space to keep track of things we're updating **
    #set( $expNames  = {} )
    #set( $expValues = {} )
    #set( $expSet = {} )
    #set( $expAdd = {} )
    #set( $expRemove = [] )

    ## Increment "version" by 1 **
    $!{expAdd.put("version", ":newVersion")}
    $!{expValues.put(":newVersion", { "N" : 1 })}

    ## Iterate through each argument, skipping "id" and "expectedVersion" **
    #foreach( $entry in $context.arguments.entrySet() )
        #if( $entry.key != "id" && $entry.key != "expectedVersion" )
            #if( (!$entry.value) && ("$!{entry.value}" == "") )
                ## If the argument is set to "null", then remove that attribute from the item in DynamoDB **

                #set( $discard = ${expRemove.add("#${entry.key}")} )
                $!{expNames.put("#${entry.key}", "$entry.key")}
            #else
                ## Otherwise set (or update) the attribute on the item in DynamoDB **

                $!{expSet.put("#${entry.key}", ":${entry.key}")}
                $!{expNames.put("#${entry.key}", "$entry.key")}

                #if( $entry.key == "ups" || $entry.key == "downs" )
                    $!{expValues.put(":${entry.key}", { "N" : $entry.value })}
                #else
                    $!{expValues.put(":${entry.key}", { "S" : "${entry.value}" })}
                #end
            #end
        #end
    #end

    ## Start building the update expression, starting with attributes we're going to SET **
    #set( $expression = "" )
    #if( !${expSet.isEmpty()} )
        #set( $expression = "SET" )
        #foreach( $entry in $expSet.entrySet() )
            #set( $expression = "${expression} ${entry.key} = ${entry.value}" )
            #if ( $foreach.hasNext )
                #set( $expression = "${expression}," )
            #end
        #end
    #end

    ## Continue building the update expression, adding attributes we're going to ADD **
    #if( !${expAdd.isEmpty()} )
        #set( $expression = "${expression} ADD" )
        #foreach( $entry in $expAdd.entrySet() )
            #set( $expression = "${expression} ${entry.key} ${entry.value}" )
            #if ( $foreach.hasNext )
                #set( $expression = "${expression}," )
            #end
        #end
    #end

    ## Continue building the update expression, adding attributes we're going to REMOVE **
    #if( !${expRemove.isEmpty()} )
        #set( $expression = "${expression} REMOVE" )

        #foreach( $entry in $expRemove )
            #set( $expression = "${expression} ${entry}" )
            #if ( $foreach.hasNext )
                #set( $expression = "${expression}," )
            #end
        #end
    #end

    ## Finally, write the update expression into the document, along with any expressionNames and expressionValues **
    "update" : {
        "expression" : "${expression}"
        #if( !${expNames.isEmpty()} )
            ,"expressionNames" : $utils.toJson($expNames)
        #end
        #if( !${expValues.isEmpty()} )
            ,"expressionValues" : $utils.toJson($expValues)
        #end
    },

    "condition" : {
        "expression"       : "version = :expectedVersion",
        "expressionValues" : {
            ":expectedVersion" : $util.dynamodb.toDynamoDBJson($ctx.args.expectedVersion)
        }
    }
}
```

有关 DynamoDB `UpdateItem` API 的更多信息，请参阅 [DynamoDB API 文档](https://docs.amazonaws.cn/amazondynamodb/latest/APIReference/API_UpdateItem.html)。