Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter list objects by field value in GraphQL?

Tags:

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: https://lucasconstantino.github.io/graphiql-online/

like image 431
Janez Kuhar Avatar asked Sep 02 '25 03:09

Janez Kuhar


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
  }
}
like image 149
Janez Kuhar Avatar answered Sep 04 '25 17:09

Janez Kuhar


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.

like image 30
Noam Avatar answered Sep 04 '25 16:09

Noam