Sanjibukai

Sanjibukai

How to apply SQL array aggregation function in Ecto

Hi everybody,

Edit for TL;DR:
How I can use SQL array_agg aggregate function with an Ecto fragment.
Particularly how I can nest the selects…

Let me start with some little explanations of my problem (because it might be irrelevant in real world use case…)

Say I have Posts and Users and I want to fetch all users and also all posts associated to each user.
The association I have is only defined in the Post schema with a belongs_to :user, User
So the following give me what I want but with the User duplicated in every row:

iex> Repo.all from p in Post,
         join: u in assoc(p, :user),
         select: {u.name, p.title}
[
  {"José", "Post 1"},
  {"José", "Post 2"},
  {"Joe", "Post A"},
  {"Joe", "post B"}
]

Now what I’m wanting is to get the following:

[
  {"José", ["Post 1", "Post 2"]},
  {"Joe", ["Post A", "Post B"]}
]

I can achieve this result using Enum.reduce with a Map.update in Elixir side:

Enum.reduce(map, %{}, fn {k, v}, acc -> Map.update(acc, k, [v], &[v|&1]) end)

All of the above are examples using select and ending with results having basic typed values (like strings here). And in fact name here is to be considered unique or maybe adding the id as a key, but the point here is that I can always achieve what I want in Elixir side.

And I also know that having has_many :post on the User Schema and then using preload could do the trick but only with having the elixir Structs. I mean I didn’t managed to use select as above to just grab the user name and the video title.

Note: I know that this question might seem to mix concerns like domain and views.
In real world scenario, I would have loaded the Structs and then grab according fields within a view, etc…
But I’m asking for learning purpose.

So I wanted to know if it’s somehow possible to achieve that using more elaborated SQL queries…
I tried many naive code combinations without success…
For example, I tried to use group_by: :user but then I got an error because of the lack of aggregating function.
Then I discovered array_agg aggregate function in SQL (and postgres). I guess I need to use it somehow with fragment but I don’t have any clue how to use it (besides simple example I saw in the documentation)?

So does anyone can give me some hints…

Marked As Solved

hauleth

hauleth

from p in Post,
  join: u in assoc(p, :user),
  group_by: u.name,
  select: {u.name, fragment("array_agg(?)", p.title)}

You can clean it a little by using macro:

defmacro array_agg(field) do
  quote do: fragment("array_agg(?)", unquote(field))

from p in Post,
  join: u in assoc(p, :user),
  group_by: u.name,
  select: {u.name, array_agg(p.title)}

Or if you use many of such custom functions then I have created ecto_function which provides helper functions for defining such macros. So the above will be:

defqueryfunc array_agg(field)

from p in Post,
  join: u in assoc(p, :user),
  group_by: u.name,
  select: {u.name, array_agg(p.title)}
16
Post #2

Also Liked

Sanjibukai

Sanjibukai

Thanks for your clear answer. I appreciated how you gradually put things, finishing by presenting your package.

I took a look and it’s definitely a good idea!

rameramwe

rameramwe

Thank you very much! i was stuck for multiple hours on this :smiley:
You’re awesome!

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New

We're in Beta

About us Mission Statement