lurning too koad
lurning too koad

Reputation: 2964

AppSync query resolver: are expressionNames and expressionValues necessary?

https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html#aws-appsync-resolver-mapping-template-reference-dynamodb-query

AppSync doc says that expressionNames and expressionValues are optional fields, but they are always populated by code generation. First question, should they be included as a best practice when working with DynamoDB? If so, why?

AppSync resolver for a query on the partition key:

{
    "version": "2017-02-28",
    "operation": "Query",
    "query": {
        "expression": "#partitionKey = :partitionKey",
        "expressionNames": {
            "#partitionKey": "partitionKey"
        },
        "expressionValues": {
            ":partitionKey": {
                "S": "${ctx.args.partitionKey}"
            }
        }
    }
}

Second question, what exactly is the layman translation of the expression field here in the code above? What exactly is that statement telling DynamoDB to do? What is the use of the # in "expression": "#partitionKey = :partitionKey" and are the expression names and values just formatting safeguards?

Upvotes: 1

Views: 1925

Answers (1)

Tinou
Tinou

Reputation: 6158

Let me answer your second question first:

expressionNames

expressionNames are used for interpolation. What this means is after interpolation, this filter expression object:

"expression": "#partitionKey = :value",
"expressionNames": {
    "#partitionKey": "id"
}

will be transformed to:

"expression": "id = :value",

the #partitionKey acts as a placeholder for your column name id. '#' happens to be the delimiter.

But why?

expressionNames are necessary because certain keywords are reserved by DynamoDB, meaning you can't use these words inside a DynamoDB expression.

expressionValues

When you need to compare anything in a DynamoDB expression, you will need also to use a substitute for the actual value using a placeholder, because the DynamoDB typed value is a complex object.

In the following example:

"expression": "myKey = :partitionKey",
"expressionValues": {
    ":partitionKey": {
        "S": "123"
    }
}

:partitionKey is the placeholder for the complex value

{
    "S": "123"
}

':' is the different delimiter that tells DynamoDB to use the expressionValues map when replacing.

Why are expressionNames and expressionValues always used by code generation?

It is just simpler for the code generation logic to always use expressionNames and expressionValues because there is no need to have two code paths for reserved/non-reserved DynamoDB words. Using expressionNames will always prevent collisions!

Upvotes: 4

Related Questions