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?

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.

yurko

yurko

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

holandes22

holandes22

Thanks, I tried your approach I started by getting the tags that include the filters:

tags = from tag in Tag, where: tag.name in ^filter_tags

but now I get stuck on how to join with the entries.

Using once more the example from my post, the query above with filters [“a”, “b”] gives me 2 Tags:

Tag.name = "a" (related to entry #1) 
Tag.name = "b" (related to entries #1 and #2)

I cannot just join and get all the related entries to those 2 tags since it would return entries #1 and #2. It should instead only return entry #1 as is the one that belongs to all the filter tags.
Not sure how to check if the entries related to those tags contain all the filter_tags

Where Next?

Popular in Questions Top

New
Werner
Hi, I’m using Ubuntu 18.04 and after updating to OTP-24.0 yesterday i have this warning when I run “mix local.hex”: 14:57:30.512 [warn] ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

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
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement