holandes22
Help filtering many-to-many associations with Ecto
I have an Entry with a many-to-many relationship to Tag. Like so:
defmodule Tag do
...
schema "tags" do
field :name, :string
end
end
defmodule Entry do
...
schema "links" do
...
many_to_many :tags, Tag, join_through: "entries_tags",
end
end
Join table :entries_tags, has
:entry_id, references(:entries)
:tag_id, references(:tags)
Now, I want to filter based on a list of tags. I’m using this query
from entry in Entry,
preload: [:tags],
distinct: entry.id,
join: tag in assoc(entry, :tags),
where: tag.name in ^tags #tags is a list of strings passed as a param
The the query above gives me all the entries that have at least
one tag in the filter list. So for example, if I have 3 entries like so:
- Entry.tags = [“a”, “b”, “c”]
- Entry.tags = [“a”, “d”]
- Entry.tags = [“d”]
and I filter with tags [“a”, “b”], it will match both #1 and #2.
My problem is that I want only to get the entries that have the filter tags as a subset of
their associated tags, meaning that using the same values as in the example above, the
returned list should only contain the entry #1
Any idea how can I construct such a query?
Most Liked
michalmuskala
I think something like this should work (not tested):
from entry in Entry,
preload: [:tags],
join: tag in assoc(entry, :tags),
group_by: entry.id,
having: fragment("? <@ array_agg(?)", ^tags, tag.name)
OvermindDL1
I’d probably just do this (I don’t use invisible many-to-many joins, I like explicit tables, so I’ll imagine your entries_tags join table exposed as EntriesTags, I’ll also imagine you have a unique index field as a composite of the entry and tag foreign keys as I always do for many-to-many joins of this form, I would also add a virtual _rank field on Entry, I add that field to almost all my models just for purposes like this since Ecto has no good way to convert a struct return table to a map while adding a column (*hint*hint*, we need that)):
tags = ["a", "b"]
# Grab all entries that have these tags
squery =
from entrytag in EntriesTags,
join: tag in Tag, on: entrytag.tag_id == tag.id and tag.name in ^tags,
join: entry in Entry, on: entrytag.entry_id == entry.id,
select: %{entry | _rank: fragment("rank() OVER (PARTITION BY ?)", entrytag.tag_id)}
query =
from s in subquery(squery),
where: s._rank == ^length(tag), # Then only grab entries that have 'all' the listed tag
join: tag in assoc(entry, :tags), # Now let's preload the tags in the same query, assuming you want them, or leave out this and the next line
preload: [:tags]
results = Repo.all(query)
Another alternative is to just aggregate all the tags into an array via array_agg, however that would require adding yet another virtual field on your schema or to manually specify everything you want returned in a map, assuming you do the latter:
tags = ["a", "b"]
# Aggregate all the tags on an entry
squery =
from entry in Entry,
join: tag in assoc(entry, :tags),
group_by: entry.id,
select: %{
blah: entry.blah,
others: entry.others,
tag_names: fragment("arrray_agg(?)", tag.name),
}
# Then query that list to grab what you want:
query =
from s in subquery(squery),
where: fragment("? <@ ?", ^tags, s.tag_names)
results = Repo.all(query)
Or something like that…
holandes22
Thank you @OvermindDL1 ! your second suggestion is what ultimately made it work.
I was trying to avoid to use raw sql as I was sure that there would be a way to accomplish this with Ecto’s DSL, but I guess the option it is there to deal with things that the DSL cannot cover.
My final query looks like so
squery =
from entry in Entry,
join: tag in assoc(entry, :tags),
group_by: entry.id,
select: %{id: entry.id, tag_names: fragment("array_agg(?)", tag.name)}
from sq in subquery(squery),
join: entry, on: entry.id == sq.id,
where: fragment("? <@ ?", ^tags, sq.tag_names),
select: entry
I had to add the join in the final query to be able to return the entry based on the schema.
Selecting the fields manually as you suggested also worked but it seems tedious and would fail to add any eventual new field, although it probably is faster
I tried to avoid the join by using your suggestion of a virtual field in Entry, and making the query like so:
field :tag_names, {:array, :string}, virtual: true # Entry schema
squery =
from entry in query,
join: tag in assoc(entry, :tags),
group_by: entry.id,
select: %{entry | tag_names: fragment("array_agg(?)", tag.name)}
from sq in subquery(squery),
where: fragment("? <@ ?", ^tags, sq.tag_names)
but that raised an error (originated from the second query)
** (Ecto.SubQueryError) the following exception happened when compiling a subquery.
** (Ecto.SubQueryError) the following exception happened when compiling a subquery.
** (FunctionClauseError) no function clause matching in anonymous fn/1 in Ecto.Query.Planner.subquery_fields/2
...
Not sure what that error means, I’m guessing due to the related tags field.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance










