Why Use the Composing Queries
Learn about query composition in Ecto.
Decomposition of queries
With the addition of join
, we can start doing more extensive and detailed queries. This is an excellent time to look at one of the features of Query
that simplifies working with complicated queries—composability. Ecto allows us to break up large queries into smaller pieces that can be reassembled at will. This makes them easier to work with and will enable us to reuse parts of queries in more than one place.
Let’s say that we wanted to look up all of the albums by Miles Davis. Using joins, this query is straightforward.
q = from a in "albums",join: ar in "artists",on: a.artist_id == ar.id,where: ar.name == "Miles Davis",select: [a.title]Repo.all(q)
Now say that somewhere else in our code, we wanted a list of the tracks on those albums, not just the album titles. We’d have to rewrite the query to look like this:
q = from a in "albums",join: ar in "artists", on: a.artist_id == ar.id,join: t in "tracks", on: t.album_id == a.id,where: ar.name == "Miles Davis",select: [t.title]
This is almost identical to the first query. We just added a join
and changed the select
. It would be nice if we could reuse the same parts. Luckily, we can! To help understand how to do that, let’s zoom in on what’s going on with the from...in...
clause we’ve been using. ...