AppSync query resolver: are expressionNames and expressionValues necessary?

ε祈祈猫儿з 提交于 2019-12-08 06:30:06

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/54269487/appsync-query-resolver-are-expressionnames-and-expressionvalues-necessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!