How to query a union of types with Absinthe.Relay.Connection.from_query

I’m trying to do cursor-based pagination across a union of several different types, each representing different Ecto schemas like so:

union :event do
  types([:identify, :page, :track])

  resolve_type(fn
    %Events.Identify{}, _ -> :identify
    %Events.Page{}, _ -> :page
    %Events.Track{}, _ -> :track
  end)
end

connection(node_type: :event)

I’m trying to figure out a way to use Absinthe.Relay.Connection.from_query/4 so I can pass the pagination_args into my query and honestly not sure how to even approach the problem.

Has anyone dealt with this before or can point me in the right direction?

The way I have this working right now is to simply execute three different SQL queries and then sort them in Elixir (results = identifies ++ pages ++ tracks), then do Absinthe.Relay.Connection.from_list(results, pagination_args). This obviously means I have to do three very large queries in order to retrieve everything and is not ideal.

I attempted an approach using Ecto.Query.union/2 but really am not sure how this would work either.

Thanks in advance!

I would setup a table named something like events with a polymorphic association to the identify, page, track tables. This table would have identify_id, page_id, track_id columns.

See here for more details:
https://hexdocs.pm/ecto/Ecto.Schema.html#belongs_to/3-polymorphic-associations

You’ll have a bit more complexity to deal with in maintaining this 4th events table, but it should simplify your query logic and result in better performance.