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?
Trending in Questions
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
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
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated!
To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead.
Sta...
New
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
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app?
Looking for hints regarding:
Addi...
New
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
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
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
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
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
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
@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
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
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #performance
- #security










First Post!
yurko
I’d start with Tag and not the entry, select needed tags with OR and then join their entries
Most Liked
michalmuskala
I think something like this should work (not tested):
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_tagsjoin table exposed asEntriesTags, 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_rankfield onEntry, 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)):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: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
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:
but that raised an error (originated from the second query)
** (Ecto.SubQueryError) the following exception happened when compiling a subquery.
Not sure what that error means, I’m guessing due to the related tags field.
Last Post!
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:Or:
I don’t yet know how to turn this into Ecto but I would highly advice anyone from using a virtual
array_aggaggregation because Postgres can’t use any indexes properly with that.Hope this is useful for others too