Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a GraphQL query content using a specific value inside the content?

Tags:

graphql

gatsby

How do I filter a GraphQL query content using a specific value inside the content data. For example I have contents received as a result of the following GraphQL query.

query MyQuery {
  allPages {
    edges {
      node {
        content
      }
    }
  }
}

From the above query I have received contents as follows. I'm trying to filter out the result using the "Type" Value (Veg/Fruit). How can I filter out the veg contents to display only Fruit content.

{
  "node": {
    "content": [
      {
        "type": "Fruit",
        "value": {
          "Text": "Orange"
        }
      },
      {
        "type": "Fruit",
        "value": {
          "Text": "Apple"
        }
      }
    ]
  }
},
{
  "node": {
    "content": [
      { 
        "type": "Veg",
        "value": {
          "Text": "Broccoli"
        }
      },
      {
        "type": "Veg",
        "value": {
          "Text": "Lettuce"
        }
      }
    ]
  }
}
like image 576
Lalas M Avatar asked Oct 30 '25 09:10

Lalas M


1 Answers

Use GraphQL filters:

query MyQuery(filter: { content: { type: { eq: "Fruit" } } }) {
  allPages {
    edges {
      node {
        content
      }
    }
  }
}

Note: I'm assuming, based on your question, that type is a property inside content. Adapt it to your needs if not. Using the localhost:8000/___graphql may help you to create a proper GraphQL query within filters.

If you want to create different queries for each type of data you have, you can alias them like:

query MyQuery {
  fruit: allPages (filter: { content: { type: { eq: "Fruit" } } }) {
    edges {
      node {
        content
      }
    }
  }
  vegetables: allPages (filter: { content: { type: { eq: "Veg" } } }) {
    edges {
      node {
        content
      }
    }
  }
}

Your data, in this case, will be inside props.data.fruit or props.data.vegetables.

like image 124
Ferran Buireu Avatar answered Nov 03 '25 02:11

Ferran Buireu