53

How do you query using GraphQL in a manor similar to SQL's like operator?

Example: What users have a first name starting with jason?

select * from users where first_name like "jason%"

2 Answers 2

76

The short answer is: you don't.

The longer answer is that you have to write that code yourself. GraphQL isn't a database query language like SQL, it's an application query language. What that means is that GraphQL won't let you write arbitrary queries out of the box. It will only support the types of queries defined in your GraphQL schema.

If you want to be able to write a query that contains like, you have to

a) declare that in the schema, and b) write a resolve function that fetches the data

For example, you could have this schema:

type Query {
  users(firstName: String!): [User]
}

type User {
  firstName: String
  lastName: String
}

You would have to define the following resolve function for the users field:

{
  Query: {
    users(root, args){
      return sql.raw('SELECT * FROM `users` WHERE `firstName` LIKE ?', args.firstName);
    }
  }
}

And finally write this query to get a list of firstName and lastName of all the users that match your search criteria:

{
  users(firstName: 'jason%'){
    firstName
    lastName
  }
} 

Here's a post I wrote a while ago that clarifies some of the concepts around GraphQL: https://medium.com/apollo-stack/how-do-i-graphql-2fcabfc94a01

And here's a post that explains the interplay between GraphQL schemas and resolve functions: https://medium.com/apollo-stack/graphql-explained-5844742f195e

Sign up to request clarification or add additional context in comments.

2 Comments

the Q in graphql is misleading, is not a query language, is more like a structure language
Note that users(firstName: String): [User] with no exclamation mark after String can be used to make firstName optional. Then you can program your server so that users returns all users while users(firstName: "Max") returns only users whose first name is Max.
8

Not sure if this is relevant to you because you want it to start with "jason" (ie would return "jason bourne" but not "bourne jason") but I recently came across a way to query GraphQL in a "%Like%" manner. For your use case it would look something like this:

export const allUsersQuery = `
  query allUsers($UserName: String!){
    allUsers(
      filter: {first_name_contains: $UserName}
    ) {
      id
      first_name
      ...INSERT_OTHER_FIELDS_HERE...
    }
  }
`;

FWIW: I did this using a GraphCool BAAS. I don't think you were using GraphCool because GraphCool doesn't allow "_" in variable names.

Hope this helps someone down the line :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.