How to filter list objects by field value in GraphQL?

Say I have the following json data:

"data": { "continents": [ { "code": "AF", "name": "Africa", }, { "code": "EU", "name": "Europe" }, // ... ] } 

What would be the correct GraphQL query to fetch a list item with: code : "AF"? In other words, how to produce the following result:

"data": { "code": "AF", "name": "Africa" } 

So far, I have:

query { continents { code name } } 

but that simply returns the full array.

I've been running my examples on:

2 Answers

As it turns out, there is no built-in filter function defined on lists/arrays! GraphQL (query language) is basically about selecting fields on objects [Schemas and Types | GraphQL].

One only needs to look at the GraphQL schema in question:

type Query { continents(filter: ContinentFilterInput): [Continent!]! // ... } type Continent { code: ID! name: String! countries: [Country!]! } input ContinentFilterInput { code: StringQueryOperatorInput } input StringQueryOperatorInput { eq: String ne: String in: [String] nin: [String] regex: String glob: String } // ... 

We see that query continents has a parameter filter of input type ContinentFilterInput. That's enough information for us to start building our filter query:

query { continents(filter: ...) { code name } } 

Upon inspecting ContinentFilterInput, we observe that it has a single field code of input type StringQueryOperatorInput:

query { continents(filter: { code: ...}) { code name } } 

Finally, we find a field eq inside input type StringQueryOperatorInput which is a scalar type (String) and we are done:

query { continents(filter: { code: { eq: "AF" } }) { code name } } 

For this current example you can just do

query { continents(filter: {code: {eq: "AF"}}) { name } } 

I'd suggest to review the documentation regarding arguments since they explain it quite well.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like