Skip to content
Sandny Blog
  • Home
  • Java
  • JavaScript
  • AWS
  • Embedded
  • About
Query records for a list of keys in GraphQL AppSync

Query records for a list of keys in GraphQL…

  • September 3, 2018
  • by Coder Kai

If you are using AppSync GraphQL you must be familiar with the queries with filters. In fact, when you are creating a new type structure, AppSync provides default filters to scan an object in your data source. But how can you query records for a list of keys in GraphQL? Unfortunately, it is not defined in the default filters.

My basic requirement is like this

Query records for a list of keys in GraphQL

For example, the filter which is inserted when you are creating the data source will look like following

input EventFiltertInput {
  eventId: TableStringFilterInput
  eventName: TableStringFilterInput
  description: TableStringFilterInput
}

input TableStringFilterInput {
  ne: String
  eq: String
  le: String
  lt: String
  ge: String
  gt: String
  contains: String
  notContains: String
  between: [String]
  beginsWith: String
}

This doesn’t provide a way to fetch data for a list of eventIds. So is there a way to do this?

Query records for a list of keys in GraphQL

In order to do this, the resource that you can find in AWS are:

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

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ScanFilter.html

and

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html

In the second link you will find these ComparisonOperator in DynamoDB expressions. It states that the operators that you can use as follows

EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN

In the latter link it explains the use of ComparisonOperator as

a IN (b, c, d) — true if a is equal to any value in the list — for example, any of b, c or d. The list can contain up to 100 values, separated by commas.

So it seems like the one that I can use!

But how can I use it in AppSync GraphQL?

How to use the IN ComparisonOperator with GraphQL Expressions

After going through the documentations, the best way to implement was using VTL (Velocity Template Language: http://velocity.apache.org/engine/2.0/vtl-reference.html) which is used in resolvers. Its a very simple but powerful language that we can use to do the processing in AppSync Resolvers.

My query in GraphQL Schema looks like the following:

listEventsForEventId(eventIds: [String], limit: Int, nextToken: String): EventConnection

So the filter expression I should have something like this:

"filter": {
  "expression" : "#eventId IN (:id_1, :id_2, :id_3)",
  "expressionNames" : {
      "#eventId" : "eventId"
  },
  "expressionValues" : $utils.toJson(["event_id_1", "event_id_2", "event_id_3"])
}

This will work for a fixed number of parameters, but I need it to be dynamic for the length of the array. For this, VTL would come in handy. So first go to the AppSync and select the resolver you want to add by clicking on Attach button.

Query records for a list of keys in GraphQL - Resolver

Following was my resolver:

{
  "version": "2017-02-28",
  "operation": "Scan",
  "limit": $util.defaultIfNull($ctx.args.limit, 20),
  
  #set( $expNames  = {} )
  #set( $expValues = {} )
  #set( $expression = "#eventId IN (" )
  
  #set( $index = 0 )
  
  #foreach( $entry in $context.arguments.eventIds )
  #set( $index = $index +1 )
    #if( $entry)
     	#if ($context.arguments.eventIds.size() ==  $index) 
                #set( $expression = "${expression} :eventId${index})" ) 
        #else 
                #set( $expression = "${expression} :eventId${index}, " ) 
        #end
        $!{expValues.put(":eventId${index}", { "S" : "${entry}" })}
    #end
  #end
  
  
  "filter": {
    "expression" : "${expression}",
    "expressionNames" : {
        "#eventId" : "eventId"
    },
    "expressionValues" : $utils.toJson($expValues)
  },
  "nextToken": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.nextToken, null)),
}

And response mapping template

$util.toJson($ctx.result)

So in the resolver I first declared variables with VTL

#set( $expNames  = {} )
#set( $expValues = {} )
#set( $expression = "#eventId IN (" )

#set( $index = 0 )

This will hold the values for my expression, expressionNames and expressionValues of the filter.

Next, I will iterate through the resolver parameters to construct the filter expression I needed to execute IN ComparisonOperator

  #foreach( $entry in $context.arguments.eventIds )
  #set( $index = $index +1 )
    #if( $entry)
     	#if ($context.arguments.eventIds.size() ==  $index) 
                #set( $expression = "${expression} :eventId${index})" ) 
        #else 
                #set( $expression = "${expression} :eventId${index}, " ) 
        #end
        $!{expValues.put(":eventId${index}", { "S" : "${entry}" })}
    #end
  #end

This will set the values I needed for the filter.

Finally add it to the resolver.

"filter": {
  "expression" : "${expression}",
  "expressionNames" : {
      "#eventId" : "eventId"
  },
  "expressionValues" : $utils.toJson($expValues)
},
"nextToken": $util.toJson($util.defaultIfNullOrEmpty($ctx.args.nextToken, null)),

Thats it! you will be able to pass an array of strings for the endpoint and it will give you all the events precisely! Execute a simple query in AppSync to test it.

How to mutate AWS GraphQL using AWS Lambda
AppSync GraphQL Web App with AWS Amplify and IAM Authentication
Coder Kai
A humble developer
appsync aws ComparisonOperator graphql resolver VTL

Related articles

Copy files from S3 to PostgreSQL RDS
How to copy files from…
How to host GoDaddy domain with AWS EC2
How to host GoDaddy domain…
AWS Ingress ALB with EKS
How to use AWS Ingress…
Frequent errors with Apollo Client
Query definition in GraphQL and…
GraphQL Web App with AWS Amplify and IAM Authentication
AppSync GraphQL Web App with…
aws graphql with lambda
How to mutate AWS GraphQL…
Use AWS GraphQL for react native app
Use AWS GraphQL for React…
4 COMMENTS
  • Hairstyles
    March 13, 2022 at 11:34 am
    Reply

    Thanks for the tips you have shared here. Furthermore, I believe there are several factors which keep your car insurance policy premium all the way down. One is, to think about buying cars and trucks that are from the good directory of car insurance organizations. Cars which might be expensive tend to be at risk of being snatched. Aside from that insurance policies are also in line with the value of your car or truck, so the higher priced it is, then higher a premium you spend.

  • Fashion Styles
    March 15, 2022 at 1:59 pm
    Reply

    Hello! This is my 1st comment here so I just wanted to give a quick shout out and say I truly enjoy reading through your blog posts. Can you recommend any other blogs/websites/forums that cover the same subjects? Thank you!

  • MatlyTavy
    March 9, 2023 at 5:48 pm
    Reply

    Crit Care Med 1980, 8 725 728 buy cheap generic cialis uk Wait one minute in between each reading

  • actismate
    June 13, 2023 at 10:57 pm
    Reply

    online cialis 10 Histologically, the majority of breast cancers in men are infiltrating ductal carcinomas, but the entire spectrum of histological variants of breast cancer has been seen

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • android 3
  • Apollo Client 1
  • AWS 8
    • AppSync 5
    • EC2 1
    • EKS 1
    • Route53 1
    • S3 1
  • AWS Amplify 1
  • Chakra UI 1
  • Docker 1
  • Embedded 1
  • EmberJS 1
  • FCM 1
  • Godaddy 1
  • GraphQL 3
  • ios 1
  • Jasper 1
  • Java 10
    • Java 11 1
    • Java 14 1
  • JavaEE 2
  • JavaScript 39
    • Express.js 4
    • Javascript Guide 7
    • Node.js 3
    • react-native 4
    • React.js 17
    • Typescript 1
  • Kubernetes 1
  • machine learning 1
  • Maven 2
  • OCaml 3
  • PostgreSQL 1
  • Python 2
  • react-native 4
  • ReactJS 3
  • sass 1
  • Server 6
  • spark 1
  • Terraform 2
  • Ubuntu 4
  • Uncategorized 1
  • webpack 2

Recent Comments

  • Massive Health on Chakra UI Animations
  • Lexitoto on How to use AWS Ingress ALB with EKS
  • 🎁 Get free iPhone 15: http://lhci.clinic/upload/go.php 🎁 hs=84cce42c03c3755da4f2aa56ad20c93f* on How to fetch data with useEffect

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Archives

  • October 2022 3
  • September 2022 7
  • May 2022 1
  • December 2021 1
  • August 2021 1
  • July 2021 6
  • June 2021 3
  • February 2021 1
  • July 2020 1
  • December 2019 5
  • November 2019 6
  • October 2019 3
  • August 2019 1
  • March 2019 1
  • February 2019 1
  • January 2019 2
  • December 2018 1
  • September 2018 2
  • August 2018 1
  • June 2018 1
  • February 2018 1
  • November 2017 2
  • October 2017 5
  • September 2017 1
  • June 2017 1
  • May 2017 10
Sandny Blog space
Theme by Colorlib Powered by WordPress