Understanding the Problem

Anytime we need to do something like load an Ecto schema has_many association in a resolver, then query child values, we can quickly find ourselves mired in what’s referred to as the “N + 1 problem” and performing more database work than we expect. Let’s say you want to get the category for a bunch of menu items. The best way to go is to collate all the category_id values found within your set of menu items and then do a single SQL query for categories with those IDs. The N+1 problem happens when instead, you do an SQL query for each individual menu item’s category; this is where the problem gets its name. There’s 1 query to get the menu items themselves, and then N queries afterward, where N is the number of menu items. ...

Get Craft GraphQL APIs in Elixir with Absinthe now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.