Search code examples
reactjsgraphqlaws-amplify

How to use AWS Amplify GraphQL search and aggregate queries in React code?


In the current AWS Amplify React documentation there are no any examples showing how to use these GraphQL queries in React code. Can someone please post an example here. Authentication method needs be the API_KEY. Thanks.

query SearchStudentsByEmail {
  searchStudents(filter: { name: { eq: "Rene Brandel" } }) {
    items {
      id
      name
      email
    }
  }
}

Tried below, but it's returning an empty result. Zero items.

const recipes = await client.graphql({ 
            query: searchStudents,
            authMode: 'apiKey'
        }); 

Solution

  • You can use the Amplify GraphQL client to consume the API like given below. No need to specify the Auth mode if you are reading logged in user's records.

    const recipes = await client.graphql({ 
                query: searchStudents
            }); 
    

    In your case, you get an empty result because you implemented the search after creating the records. Now, only the new records will be indexed and you will not see the old records in the search results.

    For the old records to appear in the search result, you will have to backfill the search index as explained here: https://docs.amplify.aws/javascript/build-a-backend/graphqlapi/troubleshooting/#backfill-opensearch-index-from-dynamodb-table