

# AWS AppSync JavaScript function reference for DynamoDB
<a name="dynamodb-function-reference"></a>

The Amazon DynamoDB functions allow you to use JavaScript to store and retrieve data in existing Amazon DynamoDB tables in your account. This section describes the request and response handlers for supported DynamoDB operations.
+  [GetItem](dynamodb-getitem.md) — The GetItem request lets you tell the DynamoDB function to make a GetItem request to DynamoDB, and enables you to specify the key of the item in DynamoDB and whether to use a consistent read.
+  [PutItem](dynamodb-putitem.md) — The PutItem request lets you tell the DynamoDB function to make a PutItem request to DynamoDB, and enables you to specify the key of the item in DynamoDB, the full contents of the item (composed of key and attributeValues), and conditions for the operation to succeed.
+  [UpdateItem](dynamodb-updateitem.md) — The UpdateItem request enables you to tell the DynamoDB function to make a UpdateItem request to DynamoDB and allows you to specify the key of the item in DynamoDB, an update expression describing how to update the item in DynamoDB, and conditions for the operation to succeed.
+  [DeleteItem](dynamodb-deleteitem.md) — The DeleteItem request lets you tell the DynamoDB function to make a DeleteItem request to DynamoDB, and enables you to specify the key of the item in DynamoDB and conditions for the operation to succeed.
+  [Query](dynamodb-query.md) — The Query request object lets you tell the handler to make a Query request to DynamoDB, and enables you to specify the key expression, which index to use, additional filters, how many items to return, whether to use consistent reads, query direction (forward or backward), and pagination tokens.
+  [Scan](dynamodb-scan.md) — The Scan request lets you tell the DynamoDB function to make a Scan request to DynamoDB, and enables you to specify a filter to exclude results, which index to use, how many items to return, whether to use consistent reads, pagination tokens, and parallel scans.
+  [BatchGetItem](dynamodb-batchgetitem.md) — The BatchGetItem request object lets you tell the DynamoDB function to make a BatchGetItem request to DynamoDB to retrieve multiple items, potentially across multiple tables. For this request object, you must specify the table names to retrieve the items from and the keys of the items to retrieve from each table.
+  [BatchDeleteItem](dynamodb-batchdeleteitem.md) — The BatchDeleteItem request object lets you tell the DynamoDB function to make a BatchWriteItem request to DynamoDB to delete multiple items, potentially across multiple tables. For this request object, you must specify the table names to delete the items from and the keys of the items to delete from each table.
+  [BatchPutItem](dynamodb-batchputitem.md) — The BatchPutItem request object lets you tell the DynamoDB function to make a BatchWriteItem request to DynamoDB to put multiple items, potentially across multiple tables. For this request object, you must specify the table names to put the items in and the full items to put in each table.
+  [TransactGetItems](dynamodb-transactgetitems.md) — The TransactGetItems request object lets you to tell the DynamoDB function to make a TransactGetItems request to DynamoDB to retrieve multiple items, potentially across multiple tables. For this request object, you must specify the table name of each request item to retrieve the item from and the key of each request item to retrieve from each table.
+  [TransactWriteItems](dynamodb-transactwriteitems.md) — The TransactWriteItems request object lets you tell the DynamoDB function to make a TransactWriteItems request to DynamoDB to write multiple items, potentially to multiple tables. For this request object, you must specify the destination table name of each request item, the operation of each request item to perform, and the key of each request item to write.
+  [Type system (request mapping)](dynamodb-typed-values-request.md) — Learn more about how DynamoDB typing is integrated into AWS AppSync requests.
+  [Type system (response mapping)](dynamodb-typed-values-responses.md) — Learn more about how DynamoDB types are converted automatically to JSON in a response payload.
+  [Filters](dynamodb-filter.md) — Learn more about filters for query and scan operations.
+  [Condition expressions](dynamodb-condition-expressions.md) — Learn more about condition expressions for PutItem, UpdateItem, and DeleteItem operations.
+  [Transaction condition expressions](dynamodb-transaction-condition-expressions.md) — Learn more about condition expressions for TransactWriteItems operations.
+  [Projections](dynamodb-projections.md) — Learn more about how to specify attributes in read operations.

# GetItem
<a name="dynamodb-getitem"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `GetItem` request lets you tell the AWS AppSync DynamoDB function to make a `GetItem` request to DynamoDB, and enables you to specify:
+ The key of the item in DynamoDB
+ Whether to use a consistent read or not

The `GetItem` request has the following structure:

```
type DynamoDBGetItem = {
  operation: 'GetItem';
  key: { [key: string]: any };
  consistentRead?: ConsistentRead;
  projection?: {
    expression: string;
    expressionNames?: { [key: string]: string };
  };
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, using the DynamoDB built-in module is the recommended approach for generating accurate and efficient requests.

## GetItem fields
<a name="js-getitem-list"></a>

 **`operation`**   
The DynamoDB operation to perform. To perform the `GetItem` DynamoDB operation, this must be set to `GetItem`. This value is required.

 **`key`**   
The key of the item in DynamoDB. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This value is required.

 **`consistentRead`**   
Whether or not to perform a strongly consistent read with DynamoDB. This is optional, and defaults to `false`.

**`projection`**  
A projection that's used to specify the attributes to return from the DynamoDB operation. For more information about projections, see [Projections](dynamodb-projections.md). This field is optional.

For more information about DynamoDB type conversion, see [Type system (response mapping)](dynamodb-typed-values-responses.md).

## Examples
<a name="js-example"></a>

```
export const onPublish = {
  request: (ctx) => ({
    operation : "GetItem",
    key : util.dynamodb.toMapValues({
      channel: ctx.info.channelNamespace.name, 
      id: ctx.events[0].payload.id}),
    consistentRead : true
  }),
  response(ctx) {
    return [{
      id: ctx.event[0].id,
      payload: ctx.result
    }]
  }
}
```

The following example demonstrates DynamoDB utils.

```
import * as ddb from '@aws-appsync/utils/dynamodb'
export const onPublish = {
  request: (ctx) => ddb.get({
    key: {
      channel: ctx.info.channelNamespace.name, 
      id: ctx.events[0].payload.id
    },
    consistentRead: true
  }),
  response(ctx) {
    return [{
      id: ctx.event[0].id,
      payload: ctx.result
    }]
  }
}
```

For more information about the DynamoDB `GetItem` API, see the [DynamoDB API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_GetItem.html).

# PutItem
<a name="dynamodb-putitem"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `PutItem` request enables you to create or replace items in DynamoDB through AWS AppSync. The request specifies the following:
+ Item Key: The unique identifier for the DynamoDB item
+ Item Contents: The complete item data, including both the `key` and `attributeValues`
+ Operation Conditions (optional): Rules that must be met for the operation to proceed

The `PutItem` request has the following structure:

```
type DynamoDBPutItemRequest = {
  operation: 'PutItem';
  key: { [key: string]: any };
  attributeValues: { [key: string]: any};
  condition?: ConditionCheckExpression;
  customPartitionKey?: string;
  populateIndexFields?: boolean;
  _version?: number;
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, we recommend using the DynamoDB built-in module for generating accurate and efficient requests.

## PutItem fields
<a name="js-putitem-list"></a>

 **`operation`**   
The DynamoDB operation to perform. To perform the `PutItem` DynamoDB operation, this must be set to `PutItem`. This value is required.

 **`key`**   
The key of the item in DynamoDB. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This value is required.

 **`attributeValues`**   
The rest of the attributes of the item to be put into DynamoDB. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This field is optional.

 **`condition`**   
A condition to determine if the request should succeed or not, based on the state of the object already in DynamoDB. If no condition is specified, the `PutItem` request overwrites any existing entry for that item. For more information about conditions, see [Condition expressions](dynamodb-condition-expressions.md). This value is optional.

 **`_version`**   
A numeric value that represents the latest known version of an item. This value is optional. This field is used for *Conflict Detection* and is only supported on versioned data sources.

**`customPartitionKey`**  
When enabled, this string value modifies the format of the `ds_sk` and `ds_pk` records used by the delta sync table when versioning has been enabled (for more information, see [Conflict detection and sync](https://docs.aws.amazon.com/appsync/latest/devguide/conflict-detection-and-sync.html) in the *AWS AppSync Developer Guide*). When enabled, the processing of the `populateIndexFields` entry is also enabled. This field is optional.  
*Not supported in AWS AppSync Events*

**`populateIndexFields`**  
A boolean value that, when enabled **along with the `customPartitionKey`**, creates new entries for each record in the delta sync table, specifically in the `gsi_ds_pk` and `gsi_ds_sk` columns. For more information, see [Conflict detection and sync](https://docs.aws.amazon.com/appsync/latest/devguide/conflict-detection-and-sync.html) in the *AWS AppSync Developer Guide*. This field is optional.   
The item written to DynamoDB is automatically converted to JSON primitive types and is available in the context result (`context.result`).

For more information about DynamoDB type conversion, see [Type system (response mapping)](dynamodb-typed-values-responses.md).

For more information about the DynamoDB `PutItem` API, see the [DynamoDB API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_PutItem.html).

# UpdateItem
<a name="dynamodb-updateitem"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `UpdateItem` request enables you to modify existing items in DynamoDB through AWS AppSync. The request specifies the following:
+ Item Key: The unique identifier for the DynamoDB item to update
+ Item Expression: Describes how to modify the item in DynamoDB
+ Operation Conditions (optional): Rules that must be met for the update to proceed

The `UpdateItem` request has the following structure:

```
type DynamoDBUpdateItemRequest = {
  operation: 'UpdateItem';
  key: { [key: string]: any };
  update: {
    expression: string;
    expressionNames?: { [key: string]: string };
    expressionValues?: { [key: string]: any };
  };
  condition?: ConditionCheckExpression;
  customPartitionKey?: string;
  populateIndexFields?: boolean;
  _version?: number;
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, we recommend using the DynamoDB built-in module for generating accurate and efficient requests.

## UpdateItem fields
<a name="js-updateitem-list"></a>

 **`operation`**   
The DynamoDB operation to perform. To perform the `UpdateItem` DynamoDB operation, this must be set to `UpdateItem`. This value is required.

 **`key`**   
The key of the item in DynamoDB. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about specifying a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This value is required.

 **`update`**   
The `update` section lets you specify an update expression that describes how to update the item in DynamoDB. For more information about how to write update expressions, see the [DynamoDB UpdateExpressions documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html). This section is required.  
The `update` section has three components:    
** `expression` **  
The update expression. This value is required.  
** `expressionNames` **  
The substitutions for expression attribute *name* placeholders, in the form of key-value pairs. The key corresponds to a name placeholder used in the `expression`, and the value must be a string corresponding to the attribute name of the item in DynamoDB. This field is optional, and should only be populated with substitutions for expression attribute name placeholders used in the `expression`.  
** `expressionValues` **  
The substitutions for expression attribute *value* placeholders, in the form of key-value pairs. The key corresponds to a value placeholder used in the `expression`, and the value must be a typed value. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This must be specified. This field is optional, and should only be populated with substitutions for expression attribute value placeholders used in the `expression`.

 **`condition`**   
A condition to determine if the request should succeed or not, based on the state of the object already in DynamoDB. If no condition is specified, the `UpdateItem` request updates the existing entry regardless of its current state. For more information about conditions, see [Condition expressions](dynamodb-condition-expressions.md). This value is optional.

 **`_version`**   
A numeric value that represents the latest known version of an item. This value is optional. This field is used for *Conflict Detection* and is only supported on versioned data sources.  
*Not supported in AWS AppSync Events*

**`customPartitionKey`**  
When enabled, this string value modifies the format of the `ds_sk` and `ds_pk` records used by the delta sync table when versioning has been enabled (for more information, see [Conflict detection and sync](https://docs.aws.amazon.com/appsync/latest/devguide/conflict-detection-and-sync.html) in the *AWS AppSync Developer Guide*). When enabled, the processing of the `populateIndexFields` entry is also enabled. This field is optional.  
*Not supported in AWS AppSync Events*

**`populateIndexFields`**  
A boolean value that, when enabled **along with the `customPartitionKey`**, creates new entries for each record in the delta sync table, specifically in the `gsi_ds_pk` and `gsi_ds_sk` columns. For more information, see [Conflict detection and sync](https://docs.aws.amazon.com/appsync/latest/devguide/conflict-detection-and-sync.html) in the *AWS AppSync Developer Guide*. This field is optional.  
*Not supported in AWS AppSync Events*

# DeleteItem
<a name="dynamodb-deleteitem"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `DeleteItem` request enables you to delete an item in a DynamoDB table. The request specifies the following:
+ The key of the item in DynamoDB
+ Conditions for the operation to succeed

The `DeleteItem` request has the following structure:

```
type DynamoDBDeleteItemRequest = {
  operation: 'DeleteItem';
  key: { [key: string]: any };
  condition?: ConditionCheckExpression;
  customPartitionKey?: string;
  populateIndexFields?: boolean;
  _version?: number;
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, we recommend using the DynamoDB built-in module for generating accurate and efficient requests.

## DeleteItem fields
<a name="js-deleteitem-list"></a>

** `operation` **  
The DynamoDB operation to perform. To perform the `DeleteItem` DynamoDB operation, this must be set to `DeleteItem`. This value is required.

** `key` **  
The key of the item in DynamoDB. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about specifying a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This value is required.

** `condition` **  
A condition to determine if the request should succeed or not, based on the state of the object already in DynamoDB. If no condition is specified, the `DeleteItem` request deletes an item regardless of its current state. For more information about conditions, see [Condition expressions](dynamodb-condition-expressions.md). This value is optional.

** `_version` **  
A numeric value that represents the latest known version of an item. This value is optional. This field is used for *Conflict Detection* and is only supported on versioned data sources.  
*Not supported in AWS AppSync Events*

**`customPartitionKey`**  
When enabled, this string value modifies the format of the `ds_sk` and `ds_pk` records used by the delta sync table when versioning has been enabled (for more information, see [Conflict detection and sync](https://docs.aws.amazon.com/appsync/latest/devguide/conflict-detection-and-sync.html) in the *AWS AppSync Developer Guide*). When enabled, the processing of the `populateIndexFields` entry is also enabled. This field is optional.  
*Not supported in AWS AppSync Events*

**`populateIndexFields`**  
A boolean value that, when enabled **along with the `customPartitionKey`**, creates new entries for each record in the delta sync table, specifically in the `gsi_ds_pk` and `gsi_ds_sk` columns. For more information, see [Conflict detection and sync](https://docs.aws.amazon.com/appsync/latest/devguide/conflict-detection-and-sync.html) in the *AWS AppSync Developer Guide*. This field is optional.   
*Not supported in AWS AppSync Events*

For more information about the DynamoDB `DeleteItem` API, see the [DynamoDB API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DeleteItem.html).

# Query
<a name="dynamodb-query"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `Query` request enables you to efficiently select all items in a DynamoDB table that match a key condition. The request specifies the following:
+ Key expression
+ Which index to use
+ Any additional filter
+ How many items to return
+ Whether to use consistent reads
+ Query direction (forward or backward)
+ Pagination token

The `Query` request object has the following structure:

```
type DynamoDBQueryRequest = {
  operation: 'Query';
  query: {
    expression: string;
    expressionNames?: { [key: string]: string };
    expressionValues?: { [key: string]: any };
  };
  index?: string;
  nextToken?: string;
  limit?: number;
  scanIndexForward?: boolean;
  consistentRead?: boolean;
  select?: 'ALL_ATTRIBUTES' | 'ALL_PROJECTED_ATTRIBUTES' | 'SPECIFIC_ATTRIBUTES';
  filter?: {
    expression: string;
    expressionNames?: { [key: string]: string };
    expressionValues?: { [key: string]: any };
  };
  projection?: {
    expression: string;
    expressionNames?: { [key: string]: string };
  };
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, we recommend using the DynamoDB built-in module for generating accurate and efficient requests.

## Query fields
<a name="js-query-list"></a>

** `operation` **  
The DynamoDB operation to perform. To perform the `Query` DynamoDB operation, this must be set to `Query`. This value is required.

** `query` **  
The `query` section lets you specify a key condition expression that describes which items to retrieve from DynamoDB. For more information about how to write key condition expressions, see the [DynamoDB KeyConditions documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.KeyConditions.html) . This section must be specified.    
** `expression` **  
The query expression. This field must be specified.  
** `expressionNames` **  
The substitutions for expression attribute *name* placeholders, in the form of key-value pairs. The key corresponds to a name placeholder used in the `expression`, and the value must be a string corresponding to the attribute name of the item in DynamoDB. This field is optional, and should only be populated with substitutions for expression attribute name placeholders used in the `expression`.  
** `expressionValues` **  
The substitutions for expression attribute *value* placeholders, in the form of key-value pairs. The key corresponds to a value placeholder used in the `expression`, and the value must be a typed value. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This value is required. This field is optional, and should only be populated with substitutions for expression attribute value placeholders used in the `expression`.

** `filter` **  
An additional filter that can be used to filter the results from DynamoDB before they are returned. For more information about filters, see [Filters](dynamodb-filter.md). This field is optional.

** `index` **  
The name of the index to query. The DynamoDB query operation allows you to scan on Local Secondary Indexes and Global Secondary Indexes in addition to the primary key index for a hash key. If specified, this tells DynamoDB to query the specified index. If omitted, the primary key index is queried.

** `nextToken` **  
The pagination token to continue a previous query. This would have been obtained from a previous query. This field is optional.

** `limit` **  
The maximum number of items to evaluate (not necessarily the number of matching items). This field is optional.

** `scanIndexForward` **  
A boolean indicating whether to query forwards or backwards. This field is optional, and defaults to `true`.

** `consistentRead` **  
A boolean indicating whether to use consistent reads when querying DynamoDB. This field is optional, and defaults to `false`.

** `select` **  
By default, the AWS AppSync DynamoDB resolver only returns attributes that are projected into the index. If more attributes are required, you can set this field. This field is optional. The supported values are:    
** `ALL_ATTRIBUTES` **  
Returns all of the item attributes from the specified table or index. If you query a local secondary index, DynamoDB fetches the entire item from the parent table for each matching item in the index. If the index is configured to project all item attributes, all of the data can be obtained from the local secondary index and no fetching is required.  
** `ALL_PROJECTED_ATTRIBUTES` **  
Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying `ALL_ATTRIBUTES`.  
**`SPECIFIC_ATTRIBUTES`**  
Returns only the attributes listed in the `projection`'s `expression`. This return value is equivalent to specifying the `projection`'s `expression` without specifying any value for `Select`.

**`projection`**  
A projection that's used to specify the attributes to return from the DynamoDB operation. For more information about projections, see [Projections](dynamodb-projections.md). This field is optional.

For more information about the DynamoDB `Query` API, see the [DynamoDB API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html).

# Scan
<a name="dynamodb-scan"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `Scan` request scans for items across a DynamoDB table. The request specifies the following:
+ A filter to exclude results
+ Which index to use
+ How many items to return
+ Whether to use consistent reads
+ Pagination token
+ Parallel scans

The `Scan` request object has the following structure:

```
type DynamoDBScanRequest = {
  operation: 'Scan';
  index?: string;
  limit?: number;
  consistentRead?: boolean;
  nextToken?: string;
  totalSegments?: number;
  segment?: number;
  filter?: {
    expression: string;
    expressionNames?: { [key: string]: string };
    expressionValues?: { [key: string]: any };
  };
  projection?: {
    expression: string;
    expressionNames?: { [key: string]: string };
  };
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, we recommend using the DynamoDB built-in module for generating accurate and efficient requests.

## Scan fields
<a name="js-scan-list"></a>

** `operation` **  
The DynamoDB operation to perform. To perform the `Scan` DynamoDB operation, this must be set to `Scan`. This value is required.

** `filter` **  
A filter that can be used to filter the results from DynamoDB before they are returned. For more information about filters, see [Filters](dynamodb-filter.md). This field is optional.

** `index` **  
The name of the index to query. The DynamoDB query operation allows you to scan on Local Secondary Indexes and Global Secondary Indexes in addition to the primary key index for a hash key. If specified, this tells DynamoDB to query the specified index. If omitted, the primary key index is queried.

** `limit` **  
The maximum number of items to evaluate at a single time. This field is optional.

** `consistentRead` **  
A Boolean that indicates whether to use consistent reads when querying DynamoDB. This field is optional, and defaults to `false`.

** `nextToken` **  
The pagination token to continue a previous query. This would have been obtained from a previous query. This field is optional.

** `select` **  
By default, the AWS AppSync DynamoDB function only returns whatever attributes are projected into the index. If more attributes are required, then this field can be set. This field is optional. The supported values are:    
** `ALL_ATTRIBUTES` **  
Returns all of the item attributes from the specified table or index. If you query a local secondary index, DynamoDB fetches the entire item from the parent table for each matching item in the index. If the index is configured to project all item attributes, all of the data can be obtained from the local secondary index and no fetching is required.  
** `ALL_PROJECTED_ATTRIBUTES` **  
Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying `ALL_ATTRIBUTES`.  
**`SPECIFIC_ATTRIBUTES`**  
Returns only the attributes listed in the `projection`'s `expression`. This return value is equivalent to specifying the `projection`'s `expression` without specifying any value for `Select`.

** `totalSegments` **  
The number of segments to partition the table by when performing a parallel scan. This field is optional, but must be specified if `segment` is specified.

** `segment` **  
The table segment in this operation when performing a parallel scan. This field is optional, but must be specified if `totalSegments` is specified.

**`projection`**  
A projection that's used to specify the attributes to return from the DynamoDB operation. For more information about projections, see [Projections](dynamodb-projections.md). This field is optional.

The results have the following structure:

```
{
    items = [ ... ],
    nextToken = "a pagination token",
    scannedCount = 10
}
```

The fields are defined as follows:

** `items` **  
A list containing the items returned by the DynamoDB scan.

** `nextToken` **  
If there might be more results, `nextToken` contains a pagination token that you can use in another request. AWS AppSync encrypts and obfuscates the pagination token returned from DynamoDB. This prevents your table data from being inadvertently leaked to the caller. Also, these pagination tokens can’t be used across different functions.

** `scannedCount` **  
The number of items that were retrieved by DynamoDB before a filter expression (if present) was applied.

For more information about the DynamoDB `Scan` API, see the [DynamoDB API documentation](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html).

# BatchGetItem
<a name="dynamodb-batchgetitem"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `BatchGetItem` request object enables you to retrieve multiple items, potentially across multiple DynamoDB tables. For this request object, you must specify the following:
+ The names of the table to retrieve the items from
+ The keys of the items to retrieve from each table

The DynamoDB `BatchGetItem` limits apply and **no condition expression** can be provided.

The `BatchGetItem` request object has the following structure:

```
type DynamoDBBatchGetItemRequest = {
  operation: 'BatchGetItem';
  tables: {
    [tableName: string]: {
      keys: { [key: string]: any }[];
      consistentRead?: boolean; 
      projection?: {
        expression: string;
        expressionNames?: { [key: string]: string };
      };
    };
  };
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, we recommend using the DynamoDB built-in module for generating accurate and efficient requests.

## BatchGetItem fields
<a name="js-BatchGetItem-list"></a>

** `operation` **  
The DynamoDB operation to perform. To perform the `BatchGetItem` DynamoDB operation, this must be set to `BatchGetItem`. This value is required.

** `tables` **  
The DynamoDB tables to retrieve the items from. The value is a map where table names are specified as the keys of the map. At least one table must be provided. This `tables` value is required.    
** `keys` **  
List of DynamoDB keys representing the primary key of the items to retrieve. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md).  
** `consistentRead` **  
Whether to use a consistent read when executing a *GetItem* operation. This value is optional and defaults to *false*.  
**`projection`**  
A projection that's used to specify the attributes to return from the DynamoDB operation. For more information about projections, see [Projections](dynamodb-projections.md). This field is optional.

Things to remember:
+ If an item has not been retrieved from the table, a *null* element appears in the data block for that table.
+ Invocation results are sorted per table, based on the order in which they were provided inside the request object.
+ Each `Get` command inside a `BatchGetItem` is atomic, however, a batch can be partially processed. If a batch is partially processed due to an error, the unprocessed keys are returned as part of the invocation result inside the *unprocessedKeys* block.
+  `BatchGetItem` is limited to 100 keys.

Response structure

```
type Response = {
  data: {
    [tableName: string]: {[key: string]: any}[]
  }
  unprocessedKeys: {
    [tableName: string]: {[key: string]: string}[]
  }
}
```

# BatchDeleteItem
<a name="dynamodb-batchdeleteitem"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `BatchDeleteItem` request deletes multiple items, potentially across multiple tables using a `BatchWriteItem` request. The request specifies the following:
+ The names of the tables to delete the items from
+ The keys of the items to delete from each table

The DynamoDB `BatchWriteItem` limits apply and **no condition expression** can be provided.

The `BatchDeleteItem` request object has the following structure:

```
type DynamoDBBatchDeleteItemRequest = {
  operation: 'BatchDeleteItem';
  tables: {
    [tableName: string]: { [key: string]: any }[];
  };
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, we recommend using the DynamoDB built-in module for generating accurate and efficient requests.

## BatchDeleteItem fields
<a name="js-BatchDeleteItem-list"></a>

** `operation` **  
The DynamoDB operation to perform. To perform the `BatchDeleteItem` DynamoDB operation, this must be set to `BatchDeleteItem`. This value is required.

** `tables` **  
The DynamoDB tables to delete the items from. Each table is a list of DynamoDB keys representing the primary key of the items to delete. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). At least one table must be provided. The `tables` value is required.

Things to remember:
+ Contrary to the `DeleteItem` operation, the fully deleted item isn’t returned in the response. Only the passed key is returned.
+ If an item has not been deleted from the table, a *null* element appears in the data block for that table.
+ Invocation results are sorted per table, based on the order in which they were provided inside the request object.
+ Each `Delete` command inside a `BatchDeleteItem` is atomic. However a batch can be partially processed. If a batch is partially processed due to an error, the unprocessed keys are returned as part of the invocation result inside the *unprocessedKeys* block.
+  `BatchDeleteItem` is limited to 25 keys.
+ This operation **is not** supported when used with conflict detection. Using both at the same time may result in an error.

Response structure (in `ctx.result)`

```
type Response = {
  data: {
    [tableName: string]: {[key: string]: any}[]
  }
  unprocessedKeys: {
    [tableName: string]: {[key: string]: any}[]
  }
}
```

The `ctx.error` contains details about the error. The keys **data**, **unprocessedKeys**, and each table key that was provided in the function request object are guaranteed to be present in the invocation result. Items that have been deleted are present in the **data** block. Items that haven’t been processed are marked as *null* inside the data block and are placed inside the **unprocessedKeys** block.

# BatchPutItem
<a name="dynamodb-batchputitem"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `BatchPutItem` request enables you to put multiple items, potentially across multiple DynamoDB tables using a `BatchWriteItem` request. The request specifies the following:
+ The names of the tables to put the items in
+ The full list of items to put in each table

The DynamoDB `BatchWriteItem` limits apply and **no condition expression** can be provided.

The `BatchPutItem` request object has the following structure:

```
type DynamoDBBatchPutItemRequest = {
  operation: 'BatchPutItem';
  tables: {
    [tableName: string]: { [key: string]: any}[];
  };
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, we recommend using the DynamoDB built-in module for generating accurate and efficient requests.

## BatchPutItem fields
<a name="js-BatchPutItem-list"></a>

** `operation` **  
The DynamoDB operation to perform. To perform the `BatchPutItem` DynamoDB operation, this must be set to `BatchPutItem`. This value is required.

** `tables` **  
The DynamoDB tables to put the items in. Each table entry represents a list of DynamoDB items to insert for this specific table. At least one table must be provided. This value is required.

Things to remember:
+ The fully inserted items are returned in the response, if successful.
+ If an item hasn’t been inserted in the table, a *null* element is displayed in the data block for that table.
+ The inserted items are sorted per table, based on the order in which they were provided inside the request object.
+ Each `Put` command inside a `BatchPutItem` is atomic, however, a batch can be partially processed. If a batch is partially processed due to an error, the unprocessed keys are returned as part of the invocation result inside the *unprocessedKeys* block.
+  `BatchPutItem` is limited to 25 items.
+ This operation **is not** supported when used with conflict detection. Using both at the same time may result in an error.

Response structure (in `ctx.result)`

```
type Response = {
  data: {
    [tableName: string]: {[key: string]: any}[]
  }
  unprocessedItems: {
    [tableName: string]: {[key: string]: any}[]
  }
}
```

The `ctx.error` contains details about the error. The keys **data**, **unprocessedItems**, and each table key that was provided in the request object are guaranteed to be present in the invocation result. Items that have been inserted are in the **data** block. Items that haven’t been processed are marked as *null* inside the data block and are placed inside the **unprocessedItems** block.

# TransactGetItems
<a name="dynamodb-transactgetitems"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `TransactGetItems` request object retrieves multiple items, potentially across multiple DynamoDB tables in a single transaction. The request specifies the following:
+ The names of the tables to retrieve each item from
+ The key of each request item to retrieve from each table

The DynamoDB `TransactGetItems` limits apply and **no condition expression** can be provided.

The `TransactGetItems` request object has the following structure:

```
type DynamoDBTransactGetItemsRequest = {
  operation: 'TransactGetItems';
  transactItems: { table: string; key: { [key: string]: any }; projection?: { expression: string; expressionNames?: { [key: string]: string }; }[];
  };
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, we recommend using the DynamoDB built-in module for generating accurate and efficient requests.

## TransactGetItems fields
<a name="js-TransactGetItems-list"></a>

** `operation` **  
The DynamoDB operation to perform. To perform the `TransactGetItems` DynamoDB operation, this must be set to `TransactGetItems`. This value is required.

** `transactItems` **  
The request items to include. The value is an array of request items. At least one request item must be provided. This `transactItems` value is required.    
** `table` **  
The DynamoDB table to retrieve the item from. The value is a string of the table name. This `table` value is required.  
** `key` **  
The DynamoDB key representing the primary key of the item to retrieve. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md).  
**`projection`**  
A projection that's used to specify the attributes to return from the DynamoDB operation. For more information about projections, see [Projections](dynamodb-projections.md). This field is optional.

Things to remember:
+ If a transaction succeeds, the order of retrieved items in the `items` block will be the same as the order of request items.
+ Transactions are performed in an all-or-nothing way. If any request item causes an error, the whole transaction will not be performed and error details will be returned.
+ A request item being unable to be retrieved is not an error. Instead, a *null* element appears in the *items* block in the corresponding position.
+ If the error of a transaction is *TransactionCanceledException*, the `cancellationReasons` block will be populated. The order of cancellation reasons in `cancellationReasons` block will be the same as the order of request items.
+  `TransactGetItems` is limited to 100 request items.

Response structure (in `ctx.result`)

```
type Response = {
  items?: ({[key: string]: any} | null)[];
  cancellationReasons?: {
    type: string;
    message: string;
  }[]
}
```

The `ctx.error` contains details about the error. The keys **items** and **cancellationReasons** are guaranteed to be present in `ctx.result`.

# TransactWriteItems
<a name="dynamodb-transactwriteitems"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

The `TransactWriteItems` request writes multiple items, potentially to multiple DynamoDB tables. The request specifies the following:
+ The destination table name of each request item
+ The operation to perform for each request item. There are four types of operations that are supported: *PutItem*, *UpdateItem*, *DeleteItem*, and *ConditionCheck* 
+ The key of each request item to write

The DynamoDB `TransactWriteItems` limits apply.

The `TransactWriteItems` request object has the following structure:

```
type DynamoDBTransactWriteItemsRequest = {
  operation: 'TransactWriteItems';
  transactItems: TransactItem[];
};
type TransactItem =
  | TransactWritePutItem
  | TransactWriteUpdateItem
  | TransactWriteDeleteItem
  | TransactWriteConditionCheckItem;
type TransactWritePutItem = {
  table: string;
  operation: 'PutItem';
  key: { [key: string]: any };
  attributeValues: { [key: string]: string};
  condition?: TransactConditionCheckExpression;
};
type TransactWriteUpdateItem = {
  table: string;
  operation: 'UpdateItem';
  key: { [key: string]: any };
  update: DynamoDBExpression;
  condition?: TransactConditionCheckExpression;
};
type TransactWriteDeleteItem = {
  table: string;
  operation: 'DeleteItem';
  key: { [key: string]: any };
  condition?: TransactConditionCheckExpression;
};
type TransactWriteConditionCheckItem = {
  table: string;
  operation: 'ConditionCheck';
  key: { [key: string]: any };
  condition?: TransactConditionCheckExpression;
};
type TransactConditionCheckExpression = {
  expression: string;
  expressionNames?: { [key: string]: string};
  expressionValues?: { [key: string]: any};
  returnValuesOnConditionCheckFailure: boolean;
};
```

The TypeScript definition above shows all available fields for the request. While you can construct this request manually, we recommend using the DynamoDB built-in module for generating accurate and efficient requests.

## TransactWriteItems fields
<a name="js-TransactWriteItems-list"></a>

**The fields are defined as follows: **    
** `operation` **  
The DynamoDB operation to perform. To perform the `TransactWriteItems` DynamoDB operation, this must be set to `TransactWriteItems`. This value is required.  
** `transactItems` **  
The request items to include. The value is an array of request items. At least one request item must be provided. This `transactItems` value is required.  
For `PutItem`, the fields are defined as follows:    
** `table` **  
The destination DynamoDB table. The value is a string of the table name. This `table` value is required.  
** `operation` **  
The DynamoDB operation to perform. To perform the `PutItem` DynamoDB operation, this must be set to `PutItem`. This value is required.  
** `key` **  
The DynamoDB key representing the primary key of the item to put. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This value is required.  
** `attributeValues` **  
The rest of the attributes of the item to be put into DynamoDB. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This field is optional.  
** `condition` **  
A condition to determine if the request should succeed or not, based on the state of the object already in DynamoDB. If no condition is specified, the `PutItem` request overwrites any existing entry for that item. You can specify whether to retrieve the existing item back when condition check fails. For more information about transactional conditions, see [Transaction condition expressions](dynamodb-transaction-condition-expressions.md). This value is optional.
For `UpdateItem`, the fields are defined as follows:    
** `table` **  
The DynamoDB table to update. The value is a string of the table name. This `table` value is required.  
** `operation` **  
The DynamoDB operation to perform. To perform the `UpdateItem` DynamoDB operation, this must be set to `UpdateItem`. This value is required.  
** `key` **  
The DynamoDB key representing the primary key of the item to update. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This value is required.  
** `update` **  
The `update` section lets you specify an update expression that describes how to update the item in DynamoDB. For more information about how to write update expressions, see the [DynamoDB UpdateExpressions documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html). This section is required.  
** `condition` **  
A condition to determine if the request should succeed or not, based on the state of the object already in DynamoDB. If no condition is specified, the `UpdateItem` request updates the existing entry regardless of its current state. You can specify whether to retrieve the existing item back when condition check fails. For more information about transactional conditions, see [Transaction condition expressions](dynamodb-transaction-condition-expressions.md). This value is optional.
For `DeleteItem`, the fields are defined as follows:    
** `table` **  
The DynamoDB table in which to delete the item. The value is a string of the table name. This `table` value is required.  
** `operation` **  
The DynamoDB operation to perform. To perform the `DeleteItem` DynamoDB operation, this must be set to `DeleteItem`. This value is required.  
** `key` **  
The DynamoDB key representing the primary key of the item to delete. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This value is required.  
** `condition` **  
A condition to determine if the request should succeed or not, based on the state of the object already in DynamoDB. If no condition is specified, the `DeleteItem` request deletes an item regardless of its current state. You can specify whether to retrieve the existing item back when condition check fails. For more information about transactional conditions, see [Transaction condition expressions](dynamodb-transaction-condition-expressions.md). This value is optional.
For `ConditionCheck`, the fields are defined as follows:    
** `table` **  
The DynamoDB table in which to check the condition. The value is a string of the table name. This `table` value is required.  
** `operation` **  
The DynamoDB operation to perform. To perform the `ConditionCheck` DynamoDB operation, this must be set to `ConditionCheck`. This value is required.  
** `key` **  
The DynamoDB key representing the primary key of the item to condition check. DynamoDB items may have a single hash key, or a hash key and sort key, depending on the table structure. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This value is required.  
** `condition` **  
A condition to determine if the request should succeed or not, based on the state of the object already in DynamoDB. You can specify whether to retrieve the existing item back when condition check fails. For more information about transactional conditions, see [Transaction condition expressions](dynamodb-transaction-condition-expressions.md). This value is required.

Things to remember:
+ Only keys of request items are returned in the response, if successful. The order of keys will be the same as the order of request items.
+ Transactions are performed in an all-or-nothing way. If any request item causes an error, the whole transaction will not be performed and error details will be returned.
+ No two request items can target the same item. Otherwise they will cause *TransactionCanceledException* error.
+ If the error of a transaction is *TransactionCanceledException*, the `cancellationReasons` block will be populated. If a request item’s condition check fails **and** you did not specify `returnValuesOnConditionCheckFailure` to be `false`, the item existing in the table will be retrieved and stored in `item` at the corresponding position of `cancellationReasons` block.
+  `TransactWriteItems` is limited to 100 request items.
+ This operation **is not** supported when used with conflict detection. Using both at the same time may result in an error.

Response structure (in `ctx.result`)

```
type Responser = {
  keys?: {[key: string]: string}[];
  cancellationReasons?: {
    item?: { [key: string]: any };
    type: string;
    message;
  }
}
```

The `ctx.error` contains details about the error. The keys **keys** and **cancellationReasons** are guaranteed to be present in `ctx.result`.

# Type system (request mapping)
<a name="dynamodb-typed-values-request"></a>

When using the AWS AppSync DynamoDB function to call your DynamoDB tables, you must specify your data using the DynamoDB type notation. For more information about DynamoDB data types, see the DynamoDB [Data type descriptors](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors) and [Data types](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes) documentation.

**Note**  
You don't have to use DynamoDB type notation when using the DynamoDB built-in module. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

A DynamoDB value is represented by a JSON object containing a single key-value pair. The key specifies the DynamoDB type, and the value specifies the value itself. In the following example, the key `S` denotes that the value is a string, and the value `identifier` is the string value itself.

```
{ "S" : "identifier" }
```

The JSON object can't have more than one key-value pair. If more than one key-value pair is specified, the request object isn’t parsed.

A DynamoDB value is used anywhere in a request object where you need to specify a value. Some places where you need to do this include: `key` and `attributeValue` sections, and the `expressionValues` section of expression sections. In the following example, the DynamoDB String value `identifier` is being assigned to the `id` field in a `key` section (perhaps in a `GetItem` request object).

```
"key" : {
   "id" : { "S" : "identifier" }
}
```

 **Supported Types** 

AWS AppSync supports the following DynamoDB scalar, document, and set types:

**String type `S` **  
A single string value. A DynamoDB String value is denoted by:  

```
{ "S" : "some string" }
```
An example usage is:  

```
"key" : {
   "id" : { "S" : "some string" }
}
```

**String set type `SS` **  
A set of string values. A DynamoDB String Set value is denoted by:  

```
{ "SS" : [ "first value", "second value", ... ] }
```
An example usage is:  

```
"attributeValues" : {
   "phoneNumbers" : { "SS" : [ "+1 555 123 4567", "+1 555 234 5678" ] }
}
```

**Number type `N` **  
A single numeric value. A DynamoDB Number value is denoted by:  

```
{ "N" : 1234 }
```
An example usage is:  

```
"expressionValues" : {
   ":expectedVersion" : { "N" : 1 }
}
```

**Number set type `NS` **  
A set of number values. A DynamoDB Number Set value is denoted by:  

```
{ "NS" : [ 1, 2.3, 4 ... ] }
```
An example usage is:  

```
"attributeValues" : {
   "sensorReadings" : { "NS" : [ 67.8, 12.2, 70 ] }
}
```

**Binary type `B` **  
A binary value. A DynamoDB Binary value is denoted by:  

```
{ "B" : "SGVsbG8sIFdvcmxkIQo=" }
```
Note that the value is actually a string, where the string is the base64-encoded representation of the binary data. AWS AppSync decodes this string back into its binary value before sending it to DynamoDB. AWS AppSync uses the base64 decoding scheme as defined by RFC 2045: any character that isn’t in the base64 alphabet is ignored.  
An example usage is:  

```
"attributeValues" : {
   "binaryMessage" : { "B" : "SGVsbG8sIFdvcmxkIQo=" }
}
```

**Binary set type `BS` **  
A set of binary values. A DynamoDB Binary Set value is denoted by:  

```
{ "BS" : [ "SGVsbG8sIFdvcmxkIQo=", "SG93IGFyZSB5b3U/Cg==" ... ] }
```
Note that the value is actually a string, where the string is the base64-encoded representation of the binary data. AWS AppSync decodes this string back into its binary value before sending it to DynamoDB. AWS AppSync uses the base64 decoding scheme as defined by RFC 2045: any character that is not in the base64 alphabet is ignored.  
An example usage is:  

```
"attributeValues" : {
   "binaryMessages" : { "BS" : [ "SGVsbG8sIFdvcmxkIQo=", "SG93IGFyZSB5b3U/Cg==" ] }
}
```

**Boolean type `BOOL` **  
A Boolean value. A DynamoDB Boolean value is denoted by:  

```
{ "BOOL" : true }
```
Note that only `true` and `false` are valid values.  
An example usage is:  

```
"attributeValues" : {
   "orderComplete" : { "BOOL" : false }
}
```

**List type `L` **  
A list of any other supported DynamoDB value. A DynamoDB List value is denoted by:  

```
{ "L" : [ ... ] }
```
Note that the value is a compound value, where the list can contain zero or more of any supported DynamoDB value (including other lists). The list can also contain a mix of different types.  
An example usage is:  

```
{ "L" : [
      { "S"  : "A string value" },
      { "N"  : 1 },
      { "SS" : [ "Another string value", "Even more string values!" ] }
   ]
}
```

**Map type `M` **  
Representing an unordered collection of key-value pairs of other supported DynamoDB values. A DynamoDB Map value is denoted by:  

```
{ "M" : { ... } }
```
Note that a map can contain zero or more key-value pairs. The key must be a string, and the value can be any supported DynamoDB value (including other maps). The map can also contain a mix of different types.  
An example usage is:  

```
{ "M" : {
      "someString" : { "S"  : "A string value" },
      "someNumber" : { "N"  : 1 },
      "stringSet"  : { "SS" : [ "Another string value", "Even more string values!" ] }
   }
}
```

**Null type `NULL` **  
A null value. A DynamoDB Null value is denoted by:  

```
{ "NULL" : null }
```
An example usage is:  

```
"attributeValues" : {
   "phoneNumbers" : { "NULL" : null }
}
```

For more information about each type, see the [DynamoDB documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html) .

# Type system (response mapping)
<a name="dynamodb-typed-values-responses"></a>

When receiving a response from DynamoDB, AWS AppSync automatically converts it into JSON primitive types. Each attribute in DynamoDB is decoded and returned in the response handler's context.

For example, if DynamoDB returns the following:

```
{
    "id" : { "S" : "1234" },
    "name" : { "S" : "Nadia" },
    "age" : { "N" : 25 }
}
```

When the result is returned from your handler, AWS AppSync converts it into a JSON types as:

```
{
    "id" : "1234",
    "name" : "Nadia",
    "age" : 25
}
```

This section explains how AWS AppSync converts the following DynamoDB scalar, document, and set types:

**String type `S` **  
A single string value. A DynamoDB String value is returned as a string.  
For example, if DynamoDB returned the following DynamoDB String value:  

```
{ "S" : "some string" }
```
AWS AppSync converts it to a string:  

```
"some string"
```

**String set type `SS` **  
A set of string values. A DynamoDB String Set value is returned as a list of strings.  
For example, if DynamoDB returned the following DynamoDB String Set value:  

```
{ "SS" : [ "first value", "second value", ... ] }
```
AWS AppSync converts it to a list of strings:  

```
[ "+1 555 123 4567", "+1 555 234 5678" ]
```

**Number type `N` **  
A single numeric value. A DynamoDB Number value is returned as a number.  
For example, if DynamoDB returned the following DynamoDB Number value:  

```
{ "N" : 1234 }
```
AWS AppSync converts it to a number:  

```
1234
```

**Number set type `NS` **  
A set of number values. A DynamoDB Number Set value is returned as a list of numbers.  
For example, if DynamoDB returned the following DynamoDB Number Set value:  

```
{ "NS" : [ 67.8, 12.2, 70 ] }
```
AWS AppSync converts it to a list of numbers:  

```
[ 67.8, 12.2, 70 ]
```

**Binary type `B` **  
A binary value. A DynamoDB Binary value is returned as a string containing the base64 representation of that value.  
For example, if DynamoDB returned the following DynamoDB Binary value:  

```
{ "B" : "SGVsbG8sIFdvcmxkIQo=" }
```
AWS AppSync converts it to a string containing the base64 representation of the value:  

```
"SGVsbG8sIFdvcmxkIQo="
```
Note that the binary data is encoded in the base64 encoding scheme as specified in [RFC 4648](https://tools.ietf.org/html/rfc4648) and [RFC 2045](https://tools.ietf.org/html/rfc2045).

**Binary set type `BS` **  
A set of binary values. A DynamoDB Binary Set value is returned as a list of strings containing the base64 representation of the values.  
For example, if DynamoDB returned the following DynamoDB Binary Set value:  

```
{ "BS" : [ "SGVsbG8sIFdvcmxkIQo=", "SG93IGFyZSB5b3U/Cg==" ... ] }
```
AWS AppSync converts it to a list of strings containing the base64 representation of the values:  

```
[ "SGVsbG8sIFdvcmxkIQo=", "SG93IGFyZSB5b3U/Cg==" ... ]
```
Note that the binary data is encoded in the base64 encoding scheme as specified in [RFC 4648](https://tools.ietf.org/html/rfc4648) and [RFC 2045](https://tools.ietf.org/html/rfc2045).

**Boolean type `BOOL` **  
A Boolean value. A DynamoDB Boolean value is returned as a Boolean.  
For example, if DynamoDB returned the following DynamoDB Boolean value:  

```
{ "BOOL" : true }
```
AWS AppSync converts it to a Boolean:  

```
true
```

**List type `L` **  
A list of any other supported DynamoDB value. A DynamoDB List value is returned as a list of values, where each inner value is also converted.  
For example, if DynamoDB returned the following DynamoDB List value:  

```
{ "L" : [
      { "S"  : "A string value" },
      { "N"  : 1 },
      { "SS" : [ "Another string value", "Even more string values!" ] }
   ]
}
```
AWS AppSync converts it to a list of converted values:  

```
[ "A string value", 1, [ "Another string value", "Even more string values!" ] ]
```

**Map type `M` **  
A key/value collection of any other supported DynamoDB value. A DynamoDB Map value is returned as a JSON object, where each key/value is also converted.  
For example, if DynamoDB returned the following DynamoDB Map value:  

```
{ "M" : {
      "someString" : { "S"  : "A string value" },
      "someNumber" : { "N"  : 1 },
      "stringSet"  : { "SS" : [ "Another string value", "Even more string values!" ] }
   }
}
```
AWS AppSync converts it to a JSON object:  

```
{
   "someString" : "A string value",
   "someNumber" : 1,
   "stringSet"  : [ "Another string value", "Even more string values!" ]
}
```

**Null type `NULL` **  
A null value.  
For example, if DynamoDB returned the following DynamoDB Null value:  

```
{ "NULL" : null }
```
AWS AppSync converts it to a null:  

```
null
```

# Filters
<a name="dynamodb-filter"></a>

**Note**  
We recommend using the DynamoDB built-in module to generate your request. For more information, see [Amazon DynamoDB built-in module](built-in-modules.md#DDB-built-in-module).

When querying objects in DynamoDB using the `Query` and `Scan` operations, you can optionally specify a `filter` that evaluates the results and returns only the desired values.

The filter property of a `Query` or `Scan` request has the following structure:

```
type DynamoDBExpression = {
  expression: string;
  expressionNames?: { [key: string]: string};
  expressionValues?: { [key: string]: any};
};
```

The fields are defined as follows:

** `expression` **  
The query expression. For more information about how to write filter expressions, see the [DynamoDB QueryFilter](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.QueryFilter.html) and [DynamoDB ScanFilter](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ScanFilter.html) documentation. This field must be specified.

** `expressionNames` **  
The substitutions for expression attribute *name* placeholders, in the form of key-value pairs. The key corresponds to a name placeholder used in the `expression`. The value must be a string that corresponds to the attribute name of the item in DynamoDB. This field is optional, and should only be populated with substitutions for expression attribute name placeholders used in the `expression`.

** `expressionValues` **  
The substitutions for expression attribute *value* placeholders, in the form of key-value pairs. The key corresponds to a value placeholder used in the `expression`, and the value must be a typed value. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This must be specified. This field is optional, and should only be populated with substitutions for expression attribute value placeholders used in the `expression`.

## Example
<a name="js-id18"></a>

The following example is a filter section for a request, where entries retrieved from DynamoDB are only returned if the title starts with the `title` argument. 

Here we use the `util.transform.toDynamoDBFilterExpression` to automatically create a filter from an object:

```
const filter = util.transform.toDynamoDBFilterExpression({
  title: { beginsWith: 'far away' },
});

const request = {};
request.filter = JSON.parse(filter);
```

This generates the following filter:

```
{
  "filter": {
    "expression": "(begins_with(#title,:title_beginsWith))",
    "expressionNames": { "#title": "title" },
    "expressionValues": {
      ":title_beginsWith": { "S": "far away" }
    }
  }
}
```

# Condition expressions
<a name="dynamodb-condition-expressions"></a>

When you mutate objects in DynamoDB by using the `PutItem`, `UpdateItem`, and `DeleteItem` DynamoDB operations, you can optionally specify a condition expression that controls whether the request should succeed or not, based on the state of the object already in DynamoDB before the operation is performed.

While you can construct requests manually, we recommend using the DynamoDB built-in module to generate accurate and efficient requests. In the following examples, we use the built-in module to generate requests with conditions.

The AWS AppSync DynamoDB function allows a condition expression to be specified in `PutItem`, `UpdateItem`, and `DeleteItem` request objects, and also a strategy to follow if the condition fails and the object was not updated.

## Example 1
<a name="js-id19"></a>

The following `PutItem` request object doesn’t have a condition expression. As a result, it puts an item in DynamoDB even if an item with the same key already exists, which overwrites the existing item.

```
import { util } from '@aws-appsync/utils';
import * as ddb from '@aws-appsync/utils/dynamodb';

export const onPublish = {
  request(ctx) {
    const {id, payload: item} = ctx.events[0]
    return ddb.put({ key: { id }, item })
  },
  response: (ctx) => ctx.events
}
```

## Example 2
<a name="js-id20"></a>

The following `PutItem` object does have a condition expression that allows the operation to succeed only if an item with the same key does *not* exist in DynamoDB.

```
import { util } from '@aws-appsync/utils';
import * as ddb from '@aws-appsync/utils/dynamodb';

export const onPublish = {
  request(ctx) {
    const {id, payload: item} = ctx.events[0]
    return ddb.put({
      key: { id },
      item,
      condition: {id: {attributeExists: false}}
    })
  },
  response: (ctx) => ctx.events
}
```

For more information about DynamoDB conditions expressions, see the [DynamoDB ConditionExpressions documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html) .

## Specifying a condition
<a name="dynamodb-condition-specification"></a>

The `PutItem`, `UpdateItem`, and `DeleteItem` request objects all allow an optional `condition` section to be specified. If omitted, no condition check is made. If specified, the condition must be true for the operation to succeed.

The built-in module functions create a `condition` object that has the following structure.

```
type ConditionCheckExpression = {
  expression: string;
  expressionNames?: { [key: string]: string};
  expressionValues?: { [key: string]: any};
};
```

The following fields specify the condition:

** `expression` **  
The update expression itself. For more information about how to write condition expressions, see the [DynamoDB ConditionExpressions documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html) . This field must be specified.

** `expressionNames` **  
The substitutions for expression attribute name placeholders, in the form of key-value pairs. The key corresponds to a name placeholder used in the *expression*, and the value must be a string corresponding to the attribute name of the item in DynamoDB. This field is optional, and should only be populated with substitutions for expression attribute name placeholders used in the *expression*.

** `expressionValues` **  
The substitutions for expression attribute value placeholders, in the form of key-value pairs. The key corresponds to a value placeholder used in the expression, and the value must be a typed value. For more information about how to specify a “typed value”, see [Type system (request mapping)](dynamodb-typed-values-request.md). This must be specified. This field is optional, and should only be populated with substitutions for expression attribute value placeholders used in the expression.

# Transaction condition expressions
<a name="dynamodb-transaction-condition-expressions"></a>

Transaction condition expressions are available in requests of all four types of operations in `TransactWriteItems`, namely, `PutItem`, `DeleteItem`, `UpdateItem`, and `ConditionCheck`.

For `PutItem`, `DeleteItem`, and `UpdateItem`, the transaction condition expression is optional. For `ConditionCheck`, the transaction condition expression is required.

## Example 1
<a name="js-id22"></a>

The following transactional `DeleteItem` function request handler does not have a condition expression. As a result, it deletes the item in DynamoDB.

```
export const onPublish = {
  request(ctx) {
    const table = "events"
    return ddb.transactWrite({
      items: ctx.events.map(({ payload }) => ({
        deleteItem: { table, key: { id: payload.id } }
      }))
    })
  },
  response: (ctx) => ctx.events
}
```

## Example 2
<a name="js-id23"></a>

The following transactional `DeleteItem` function request handler does have a transaction condition expression that allows the operation succeed only if the author of that post equals a certain name.

```
export const onPublish = {
  request(ctx) {
    return ddb.remove({
      items: ctx.events.map(({ payload }) => ({
        deleteItem: { 
          table: 'events', 
          key: { id: payload.id }, 
          condition: { owner: { eq: payload.owner } }
        }
      }))
    })
  },
  response: (ctx) => ctx.events
}
```

If the condition check fails, it will cause `TransactionCanceledException` and the error detail will be returned in `ctx.result.cancellationReasons`.

# Projections
<a name="dynamodb-projections"></a>

When reading objects in DynamoDB using the `GetItem`, `Scan`, `Query`, `BatchGetItem`, and `TransactGetItems` operations, you can optionally specify a projection that identifies the attributes that you want. The projection property has the following structure, which is similar to filters: 

```
type DynamoDBExpression = {
  expression: string;
  expressionNames?: { [key: string]: string}
};
```

The fields are defined as follows:

** `expression` **  
The projection expression, which is a string. To retrieve a single attribute, specify its name. For multiple attributes, the names must be comma-separated values. For more information on writing projection expressions, see the [DynamoDB projection expressions](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ProjectionExpressions.html) documentation. This field is required. 

** `expressionNames` **  
The substitutions for expression attribute *name* placeholders in the form of key-value pairs. The key corresponds to a name placeholder used in the `expression`. The value must be a string that corresponds to the attribute name of the item in DynamoDB. This field is optional and should only be populated with substitutions for expression attribute name placeholders used in the `expression`. For more information about `expressionNames`, see the [DynamoDB documentation](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html). 

## Example 1
<a name="js-id24"></a>

The following example is a projection section for a JavaScript function in which only the attributes `author` and `id` are returned from DynamoDB.

```
projection : {
    expression : "#author, id",
    expressionNames : {
        "#author" : "author"
    }
}
```

## Example 2
<a name="js-id25"></a>

The following example demonstrates that when you use the built-in DynamoDB module, you can simply pass an array for your projection.

```
export const onPublish = {
  request(ctx) {
    return ddb.batchGet({
      tables: {
        users: {
          keys: ctx.events.map(e => ({id: e.payload.id})),
          projection: ['id', 'name', 'email', 'nested.field']
        }
      }
    })
  },
  response: (ctx) => ctx.events
}
```