JSONAPI-Resources / JSONAPI-Resources/jsonapi-resources

Reducing N+1 queries by eager loading

Aperta
#485 10 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Type: Maintenance
Lingua principale
Ruby
Stelle
2.3k
Fork
546
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Descrizione

I read through the documentation and couldn't find a built-in solution to this problem. When certain models are serialized we need to make sure that the query to retrieve that entity always adds an includes to avoid all the lazy loaded N+1 queries. We can do this via records as long as the request is on the resources controller. If it's not then I couldn't see a place to extend it.

Let me give an example

class ProjectResource
  has_one :company
end
class CompanyResource
  attribute :plan_start_at

  def plan_start_at
    @model.subscription.created_at
  end
end

As you'll notice each time a company is rendered it is going to retrieve a value out of it's subscription. However, the problem comes in when we request a URL like this

/api/projects?include=company

It's using the records method off of the projects resource and even when it goes to process the include on company it's not calling records on the company resource so we end up with a separate query for every companies subscription.

Now, from what I can tell maybe this is supposed to be taken care of by also requesting the subscription like this

/api/projects?include=company,company.subscription

However this doesn't completely work since I don't need the subscription object and requesting the subscription isn't a concern of the client (since we simply need the subscription in order to calculate a property on the company.)

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia tracciando il controller delle risorse, il metodo records e l'elaborazione di include descritta per ProjectResource e CompanyResource. Riproduci il caso /api/projects?include=company e confrontalo con company.subscription; il lavoro è completato quando i dati dipendenti utilizzati dagli attributi calcolati vengono caricati eager senza richiedere ai client di richiedere quella relazione.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
rails, ruby
Ambito
api, backend, performance
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.