Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing graphql database queries

Lets say we have following graphql schema:

type Author : Object {  
  id: ID!
  name: String,
  books: [Book]
}

type Book : Object {  
  id: ID!
  title: String
  authorId: Int
  author: Author
}

And then making a query like:

{
    books: {
        id 
        title
        author { id name }
    }
}

If, for example, we have 10 books, then we will end up with 10 author queries, as the resolve function will be called for each fetched book:

select id, name from author where id = 123

Instead of this we can execute all author queries as a single query:

select id, name from author where id in (123, 456, 789, 1011)

Is there some working solutions, best practices, techniques or something that can help to achieve this?

like image 729
User Created Image Avatar asked Sep 04 '16 03:09

User Created Image


People also ask

Does GraphQL optimize query?

There are numerous optimization techniques you should consider when working with GraphQL servers, but the most common is the caching technique which returns persistent data, and also the batching technique which reduces the number of round trips your server makes to the database.

Why GraphQL is overkill?

GraphQL can be overkillSince GraphQL is so complex and powerful, it can commonly be overkill for smaller applications. If you have a simple/straight-forward app in front of you, it will be easier to work with a REST API.


1 Answers

Dataloader is your answer, it has batching feature which means that it will queue all the ids. And only once its ready it will pull it as a batch Demo can be found here: https://youtu.be/UBGzsb2UkeY (Last 5 minutes in particular) Algorithem explained can be found here: https://youtu.be/OQTnXNCDywA

Enjoy :)

like image 121
HagaiCo Avatar answered Sep 29 '22 11:09

HagaiCo