Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search string values in GraphQL

Tags:

graphql

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%"

like image 709
Jason Avatar asked Jun 23 '16 02:06

Jason


People also ask

How do I find query in GraphQL?

To view the query used to display the home page feed, click on the Feed query, and then open the “Query string” dropdown. One of our favorite features is that you can then easily run the query in the GraphiQL console with the “run in GraphiQL” button.


2 Answers

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

like image 198
helfer Avatar answered Sep 21 '22 19:09

helfer


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 :)

like image 37
Mark Miller Avatar answered Sep 24 '22 19:09

Mark Miller