Optimize GraphQL queries
Learn how to optimize your GraphQL queries to improve the performance of your application.
Query only what you need
GraphQL allows you to query only the data you need, you may be tempted to have a single query that fetch all fields of an entity of your schema. Instead, query only the fields you need.
Let's demonstrate this with an example on Category entity.
Category entity is composed of datas related to the category itself and has a datalayer to retrieve products of this category.
You may be tempted to have a single query in a GQL file that retrieve all datas of the category like this one:
query MyBigCategoryQuery($id: ID!) {
category(id: $id) {
id
name
layer {
products {
name
sku
}
}
}
}
This query will in background call the Magento API twice:
- First call to get the category datas
- Second call to get the products datas
That's a good call if you're on a category page and you want to display the category and its products.
However, let's says that you want to retrieve only the category infos and use Algolia to display products. In this case, you don't need to retrieve products datas, you can query only the category datas like this one:
query MyFastCategoryQuery($id: ID!) {
category(id: $id) {
id
name
}
}
Here, only one call will be done to the Magento API, and you will save some precious time on the server.