holandes22

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:

  1. Entry.tags = [“a”, “b”, “c”]
  2. Entry.tags = [“a”, “d”]
  3. 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?

First Post! Switch mode

yurko

yurko

I’d start with Tag and not the entry, select needed tags with OR and then join their entries

Most Liked

michalmuskala

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

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

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.

Last Post!

onnimonni

onnimonni

This conversation was a top result in Google with “Ecto many to many relationship filtering”.

I tested performance a bit today in many to many case where I have apartments table, amenities table and then join table between them.

using array_agg() was 10x slower than doing:

SELECT a.*
FROM apartments a
JOIN apartment_amenities aa ON a.id = aa.apartment_id
JOIN amenities am ON aa.amenity_id = am.id
WHERE a.city = 'Chicago'
  AND am.name IN ('fridge', 'gym')
GROUP BY a.id
HAVING COUNT(DISTINCT am.name) = 2;

Or:

SELECT a.*
FROM apartments a
JOIN apartment_amenities aa1 ON a.id = aa1.apartment_id
JOIN amenities am1 ON aa1.amenity_id = am1.id
JOIN apartment_amenities aa2 ON a.id = aa2.apartment_id
JOIN amenities am2 ON aa2.amenity_id = am2.id
WHERE a.city = 'Chicago'
  AND am1.name = 'fridge'
  AND am2.name = 'gym';

I don’t yet know how to turn this into Ecto but I would highly advice anyone from using a virtual array_agg aggregation because Postgres can’t use any indexes properly with that.

Hope this is useful for others too :bowing_man:

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement