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

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
psy-q
I’m trying to set up Emacs with elixir-ls via lsp-mode and credo via Flycheck. This should mostly be preconfigured as Flycheck picks up c...
New

Other Trending Topics Top

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
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
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
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews