Strapi Deep Filtering with Graphql

Strapi Deep Filtering with Graphql

Perform nested filtering with graphql queries in strapi

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live - John Woods

Introduction

Strapi is a Open source Node.js Headless CMS to easily build customisable APIs.

The Problem

The documentation in the link provides information on how to perform deep filtering in rest API. But it it doesnot mention about deep filtering in Graphql. In this blog I am going to show how to perform deep filtering in Strapi while using graphql.

The Solution

In this blog , I am using Strapi demo app https://github.com/strapi/foodadvisor for demostrations.

Link to graphql :https://foodadvisor-api.strapi.io/graphql

The login of Deep filtering remains same as in rest API But the syntax changes.For Example in the documentation to Find restaurants owned by a chef who belongs to a restaurant with star equal to 5 the rest query will be

GET /restaurants?chef.restaurant.star=5

Now the same query with graphql will be

query {
  restaurants(where: { chef: { restaurant: { star: 5 } } }) {
    id
    name
  }
}

We can you all the filtering options available in strapi

  • No suffix or eq: Equals
  • ne: Not equals
  • lt: Less than
  • gt: Greater than
  • lte: Less than or equal to
  • gte: Greater than or equal to
  • in: Included in an array of values
  • nin: Isn't included in an array of values
  • contains: Contains
  • ncontains: Doesn't contain
  • containss: Contains case sensitive
  • ncontainss: Doesn't contain case sensitive
  • null: Is null/Is not nul

Some example queries

Find all Restaurant where category id equals 1

query{
  restaurants(where:{
    category:{
      id:1
    }
  }){
     id
     name
    category{
      id,
      name
    }
    
  }
}

Find all the reviews of restaurant with id 2

query {
 reviews(where: { restaurant: { id: 2 } }) {
   id
   restaurant {
     id
     name
   }
 }
}

Find restaurant belongs to category id 1 and restaurant id less than 5

query{
  categories(where:{id:1}){
    id
    name
    restaurants(where:{
      id_lt:5
    }){
      id
      name
    }
  }
}

Conclusion

As per the documentation in Strapi, Deep filtering is usally not recommended as it may cause performace issue.But its always be aware of this feature.

Thanks for reading! Follow me on Github and Instagram if you want to keep in touch.

Did you like it? Why don't you try also...

Hello World.

Hello World.

A journey of a thousand miles begins with a single step.

Braft Editor - Custom Media Upload and Validation

Braft Editor - Custom Media Upload and Validation

How to implement custom upload and validation for Braft Editor media.