Search code examples
aws-amplifyaws-appsync

How to sort on a field in list query in aws-amplify?


How to sort on a field in amplify graphql api? I am trying to sort on a field while getting a list of an model.

Eg: Sorting on createdDate in listOrder query.

Any help please?


Solution

  • @key directive might be what you want.

    Suppose you are listing Orders of a specific customer by createdAt timestamp, and suppose this is your schema:

    type Order @model @key(fields: ["customerEmail", "createdAt"]) {
        customerEmail: String!
        createdAt: String!
        orderId: ID!
    }
    

    This will create a primary index with a hash key of customerEmail and a sort key of createdAt that is managed on your behalf by AppSync resolvers. This will allow you to run this query:

    query ListOrdersForJack {
      listOrders(customerEmail:"jack@gmail.com") {
        items {
          orderId
          customerEmail
          createdAt
        }
      }
    }
    

    Why no explicit sort keyword? The sorting will happen automatically because the @key specifies that the field createdAt should be used as the sort key. You can refer https://github.com/aws-amplify/amplify-cli/issues/1502 for a similar discussion.