问题描述
我正在尝试使用IN
使用列表构建AWS AppSync查询:
I am trying to build an AWS AppSync query with a list using IN
:
{
"version" : "2017-02-28",
"operation" : "Query",
"index" : "my-index",
"query" : {
"expression": "id IN :ids",
"expressionValues" : { ":ids" : $util.dynamodb.toStringSet($ctx.args.ids) }
},
"limit": $util.defaultIfNull(${ctx.args.first}, 20),
"nextToken": $util.toJson($util.defaultIfNullOrBlank($ctx.args.after, null))
}
但是,请使用以下参数进行尝试:
However, trying it out with parameters like:
query ListItemsWithIdList {
listItemsWithIdList(first:20, ids: ["id1", "id2"]) {
items {
id
}
nextToken
}
}
它抛出一个错误:
Unable to parse the JSON document: 'Unexpected character ('S' (code 83)): was expecting double-quote to start field name
at [Source: (String)\"{
\"version\" : \"2017-02-28\",
\"operation\" : \"Query\",
\"index\" : \"my-index\",
\"query\" : {
\"expression\": \"id IN :ids\",
\"expressionValues\" : { \":ids\" : {SS=[id1, id2]} }
},
\"limit\": 20,
\"nextToken\": null
}\"; line: 7, column: 47]'"
使用IN
进行查询比较运算符似乎可以;但是,如何传递String List
作为参数,并获取ID在提供的那些参数之中的结果?
It seems OK to use IN
for query comparison operator; however, how can I pass a String List
as a parameter and fetch the results whose IDs are among those parameters supplied?
编辑:更正了变量名的错字.
Corrected variable name typo.
推荐答案
我不认为AWS AppSync仅暂时支持IN
.我尝试测试您的方案并使用contains()
函数提供解决方案.
I don't think AWS AppSync support IN
just for now. I try to test your scenario and come up with a solution using contains()
function.
以下是查询后的结果:
另一种替代解决方案是使用Scan
(不推荐)
Another alternative solution is to use Scan
(not recommended)
{
"version" : "2017-02-28",
"operation" : "Scan",
"filter" : {
"expression": "contains (:authors, author)",
"expressionValues" : {
":authors" : $util.dynamodb.toDynamoDBJson($ctx.args.authors)
}
}
}
顺便说一句,AWS AppSync支持BatchGetItem
操作.您可以在单个查询中传递键列表,然后从表中返回结果.
参考: https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-batch.html
这是一个示例,我测试了它是否像魅力一样工作:
Btw, AWS AppSync support BatchGetItem
operation. You can pass a list of keys in a single query and return the results from a table.
Reference: https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-batch.html
Here is an example and I tested it worked like charm:
## REQUEST MAPPING
#set($authors = [])
#foreach( $author in $ctx.args.authors )
#set($map = {})
$util.qr($map.put("author", $util.dynamodb.toString($author)))
$util.qr($authors.add($map))
#end
{
"version" : "2018-05-29",
"operation" : "BatchGetItem",
"tables" : {
"tbDiary": {
"keys": $util.toJson($authors),
"consistentRead": true
}
}
}
## RESPONSE MAPPING
$util.toJson($ctx.result.data.tbDiary)
这篇关于使用AWS AppSync中的列表查询DynamoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!