Optimize Associations With Embedded Schemas

Learn how to optimize associations.

Disadvantages of associations

The solution to N+1 queries helps us with situations where our code makes vast numbers of queries that appear to be a simple operations. Even then, fetching associated records always requires an extra round-trip to the database, and there may be situations where we want to avoid it. We might be working with associated records that always need to be loaded along with the parents, or we may be in a performance-critical situation where we need to eke out every last ounce of speed that we can. In cases like these, Ecto provides embedded schemas.

Embedded schemas

With embedded schemas, associated records are stored in a single database column and the rest of the parent record’s values. When we load the parent record, the child records load with it. The implementation of this feature varies between databases.

  • With PostgreSQL, Ecto uses the jsonb column type to store the records as an array of key/value pairs.
  • Ecto converts the records into a JSON string for MySQL and stores them as text.
  • However, the result is the same. The embedded records are loaded into the appropriate Elixir structs and available in a single query without calling preload.

Get hands-on with 1200+ tech skills courses.