Search code examples
graphqlgraphql-java

How does GraphQL support AND-OR query conditions?


I'm new to GraphQL. There is a requirement that query all the qualified data from CUSTOMERS table, which meets condition: GENDER == 'MALE' or 'AGE' >= 20. What GQL should looks like for it?


Solution

  • Someone proposed a similar thing before but it is rejected. That means GraphQL does not support it natively and you have to roll it out by yourself.

    Several ways to do it based on what I see :

    (1) Define your own query language such as what stackoverflow or Shopify does :

    type Query{
        customers (query:String) : [Customer]
    }
    

    The query becomes :

    {
      customers (query : "GENDER == 'MALE' or 'AGE' >= 20"){
        id
        name
      }
    }
    

    (2) Define your own input object models that can cover all the required searching requirement.Prisma try to define one in OpenCRUD specification .You may take a look on it for the idea . For example , you can define an input model like :

    input CustomerFilter {
         AND        :  [CustomerFilter]
         OR         :  [CustomerFilter]
    
        # Define the fields that you support to search
         gender     : String
         gender_not : String
         ....
         ....
         ...
         ...
         age        : Int
         age_gte    : Int
    }
    
    type Query{
        customers (filter:CustomerFilter) : [Customer]
    }
    

    And the query becomes :

    {
      customers (filter : {
       OR: [
         { gender : 'MALE' } ,
         { age_gte: 20 }
        ]
      }){
        id
        name
      }
    }
    

    This is another filter model for reference. The idea is to tailor-made it such that it is just enough to handle all your application requirements without introducing any unnecessary filtering complexity.

    Also , you most probably need to consider something like pagination if it potentially will return many data. It means you have to add an offset and limit to the input arguments for each query to somehow limit the number of record returned if you are doing offset-based pagination or take a look on Relay Specification if you want to do it in the cursor-based pagination style.