GraphQL querys joins


#1

I am coding and trying to map a graphql query to get collections and child collections like this:

persons {
   id
   name
   adresses {
      id
      postalCode
   }
}

My backend database is mysql and when I fetch the data with this query the apollo server console show me that it is making a SQL SELECT to get the adress for each person, for ie:

select id, name from persons
..
select id, postalCode from adresses where idperson=1
select id, postalCode from adresses where idperson=2
select id, postalCode from adresses where idperson=3
select id, postalCode from adresses where idperson=4
.......
.....

My question is, it is normal? how the performance with a big database would be? it a better way to achieve this?


#2

This is normal, and in fact almost every app at big scale avoids doing joins if they can help it. The solution is to implement caching so that if you fetch the same object multiple times from SQL it doesn’t hit your database every time. We hope to implement this in our example app soon.


#3

So, beside chaching, would be better create two queries? one for fetch a list of persons and a second one for adresses, but only execute the second one when I want to view a particular person, is this correct?


#4

I’m not sure what you mean.


#5

@sashko Sorry if I don’t explain my example well. I mean that beside to configure caching for better performance, would be convenient to separate the query this way?

persons {
   id
   name
}

adresses(idPerson: Int) {
   id
   postalCode
}

And execute the second query only when I want to fetch the address of a specific person at a different time (not all persons at time), do you understand me?


#6

Hmm, I think the schema should probably have both, depending on what you need to load in your UI and when.


#7

Ok, thank you very much!