AWS Amplify DataStore with exists-within-array filter

Viewed 713

How can we make DataStore queries with a filter that requires a field to be in a given array? For example, say I want to get all users who's first name is in the array ["Sally", "Bob", "James"]?

This is the closest graphQL query I can create. It uses the "eq" (equals) filter operation. I'm asking if there is another filter operation that checks if the value exists within a given array?

So something like this, but instead of "eq", there would be a syntax for "exists within this array".

query MyQuery {
  listUsers(filter: {firstName: {eq: "Sally"}}) {
    items {
      firstName
      lastName
      email
    }
  }
}

Please provide the graphQL query I'm describing and also the same query in DataStore syntax. for the DataStore js api. Something that is similar to...

const users = await DataStore.query(User, (u) =>
  u.firstName('exists-within-array', ["Sally", "Bob", "James"]),
)
1 Answers

A good starting point can be found here:

How to Filter List/Queries With AND/OR operators AWS Amplify JavaScript GraphQL

The idea is to convert your array into an object that can be passed as the filter object.

let filter = {
        or: [
            {
                id: {eq:1}
            },
            {
                id: {eq:2}
            }]
    }

Try something like:

    const searchArray =  ["Sally", "Bob", "James"]
    let fieldName = "firstname";
    
    let filterMembers = searchArray.map((item)=> JSON.parse(`{"${fieldName}":{"eq":"${item}"}}`));
    let filter = {or:filterMembers};

and pass the filter object as a parameter to the Query.

Related