innocentoldguy

innocentoldguy

Hello, Elixir Forum,

I’m trying to build a query that joins four tables together and returns a map that looks like this:

IDEAL RESULT

%{
  agent_domain: "Agent Domain",
  agent_hostname: "Agent Hostname",
  organization_name: "Organization Name",
  site_name: "Site Name",
  licenses: [
    %{
      ...license keys and values.
    },
    %{
      ...license keys and values.
    }
  ]
}

So far, I have this query working:

query =
  from o in Organization,
  join: s in Site,
  join: a in Agent,
  join: al in AgentLicense,
  on:
    o.id == s.organization_id and
    s.id == a.site_id and
    a.id == al.agent_id,
  where: [id: ^id],
  select: %{
    organization_name: o.name,
    site_name: s.name,
    agent_domain_name: a.domain_name,
    agent_hostname: a.hostname,
    activation_licenses: al
  }

Which returns a structure that looks like this:

ACTUAL RESULT

[
  %{
    license: %{
      ...license keys and values.
    },
   agent_domain: "Agent Domain",
   agent_hostname: "Agent Hostname",
   organization_name: "Organization Name",
   site_name: "Site Name"
  },
  %{
    license: %ActiphyPortal.Agents.AgentLicense{
      ...license keys and values.
    },
    agent_domain: "Agent Domain",
    agent_hostname: "Agent Hostname",
    organization_name: "Organization Name",
    site_name: "Site Name"
  }
]

The ACTUAL RESULT makes sense based on my query. My question is whether or not there is a way in Ecto to keep this as one query but have Ecto nest the result so that information isn’t duplicated, like the IDEAL RESULT structure above?

Thanks in advance for your help.

Showing Posts 1 to 4

LostKobrakai

LostKobrakai

The data returned by the db will always be a list of lists of column values. Ecto has some rudimentary means of mapping the list of columns to structs or maps, … and deduplicating things like assocs, but in your case being parts of the return values deduplicated and parts not (without a known assoc tree) is not possible without postprocessing results afterwards.

chulkilee

chulkilee

You can use Repo.one/2 to fetch single result (instead of a list) from a query.

al2o3cr

al2o3cr

Here’s what I get out of this query (if it doesn’t match your application, the advice that follows is probably wrong):

  • organization has many sites
  • site has many agents
  • agent has many agent licenses

What it looks like your query is ultimately looking for is a result for each agent containing the agent’s licenses and some metadata about the agent. That query would look like:

from(a in Agent,
  join: s in Site, on: s.id == a.site_id,
  join: o in Organization, on: o.id == s.organization_id
  where: o.id == ^id,
  preload: [:licenses, site: :organization]
)
|> Enum.map(fn agent ->
  %{
    organization_name: agent.site.organization.name,
    site_name: agent.site.name,
    agent_domain_name: agent.domain_name,
    agent_hostname: agent.hostname,
    activation_licenses: agent.licenses
  }
end)

(adjust licenses above if your association isn’t named that)

This loads a little more data than strictly necessary from organizations and sites but will group the results like you’re looking for.

chulkilee

chulkilee

Oh, I misread your post :man_facepalming:

What is the id? From your ideal result, it seems like you want to query by agent id. If so, it’s better to iterate by agent_list, and join others and transform the result to your “ideal” result.

Some notes

  • If you need a list from a query, then you should chose that table for from.
  • You can preload with select - so that you don’t need to fetch all columns, if it matters
  • Don’t overuse join to fetch everything in one query - it can be actually slower then running two queries, even index is being used

Here is the one query version - joining everything, taking duplicate common fields, and cleaning up with elixir

query =
  from al in AgentLicense,
    join: a in Agent,
    join: s in Site,
    join: o in Organization,
    on:
      a.id == al.agent_id and
        a.site_id == s.id and
        s.organization_id == o.id,
    where: a.id == ^id,
    select: {
      %{agent_name: a.name, site_name: s.name, organization_name: o.name},
      al # the shole schema; or you may specify %{key: al.key} to select columns
    }

{common, licenses} =
  query
  |> Repo.all()
  |> Enum.reduce({nil, []}, fn {common, al}, {_, list} -> {common, [al | list]} end)

Map.put(common, :licenses, licenses)

However, the above approach will consume more db connection bandwidth and client side memory, since the common part is being duplicated.

To avoid that, the simplest solution is to make two queries in a transaction - 1) agent & org with agent id, and 1) agent licenses with one query.

Repo.transaction(fn ->
  query = from al in AgentLicense, where: al.agent_id == ^id
  licenses = query |> Repo.all()

  query =
    from a in Agent,
      join: s in Site,
      join: o in Organization,
      on:
        a.site_id == s.id and
          s.organization_id == o.id,
      where: a.id == ^id,
      select: %{agent_name: a.name, site_name: s.name, organization_name: o.name}

  common = query |> Repo.one()

  Map.put(common, :licenses, licenses)
end)

If you just need to access assoc from the record (e.g. agent/site/org from agent license) - then you can just use preload without join - then it ecto will preload them in separate query automatically.

— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
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
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews