bodhilogic

bodhilogic

I load a CSV into two separate tables in my database and it works great.

Now that I have moved the database to the cloud, it’s time to use batch inserts/updates, but all of the examples I find for Ecto.Multi are trivial examples and I’m not sure how to go about building a process that can ultimately do one Repo.transaction for each of the two tables, using the data that I have collected inside of a loop that steps through each row of the CSV.

I reckon I have to, somehow, incorporate the use of Multi.append but don’t really know where to start.

Does each loop create its own Multi and before the next iteration, do a Multi.append into a ‘master’ multi? Or can I just pass the ‘master’ multi, which is created outside of the loop, to the sub-processes that run ‘inner multis’ inside the loop?

I found this example, which is close to what I’m after, but it runs the transaction each time which isn’t saving me any trips to the database server.

Here is some pseudocode to show you what I’m doing:

  def parse_csv(conn, file) do
    stage_date = get_date_from_filename(file)

    File.stream!("uploads/#{file}", [:trim_bom])
    |> CSV.decode(headers: true)
    |> Stream.each(fn row -> _process_csv_row(conn, row, stage_date) end)
    |> Stream.run()

    conn
  end

  defp _process_csv_row(conn, row, stage_date) do
    tenant = tenant(conn)

    # Set ticket_params from row data

    # Build ticket changeset and do a Repo.insert_or_update
    _process_ticket(ticket_params, tenant)

    # Get the id of the ticket just inserted or updated

    # Set activity_params from row data and ticket id

    # Build activity changeset and do a Repo.insert
    _process_activity(activity_params, tenant)
  end

Showing Posts 1 to 7

blatyo

blatyo

Conduit Core Team

Hey @bodhilogic,

Ecto.Multi is for executing multiple statements in a single transaction. It doesn’t batch inserts and updates. For that, you’d want to use insert_all or update_all defined on your repo. If all of your rows are inserted/updated in a single insert_all/update_all, you won’t need a transaction, because it’ll be part of a single atomic statement. However, if your CSV is large, you will likely want to batch insert in chunks. You can split your stream into chunks by using Stream.chunk_every/2. Then you can do a batch db operation with that chunk. It is likely best to not wrap the update of all chunks in a transaction either, because inserting/updating a large amount of rows in a table, will acquire write locks for all of those rows, preventing reads for as long as the transaction is open. That can usually affect other parts of your system negatively.

bodhilogic

bodhilogic OP

Fantastic answer! Thank you so much :slight_smile:

1player

1player

To answer your question “how do I use Ecto.Multi in a loop”, you would use Enum.reduce/3 to build up the Multi as you process elements in an enumerable.

def parse(_) do
  multi = Ecto.Multi.new()

  multi = 
    File.stream!("uploads/#{file}", [:trim_bom])
    |> CSV.decode(headers: true)
    |> Enum.reduce(multi, &process_row/2)
  
  Repo.transaction(multi)
end

defp process_row(row, multi) do
  parsed_row = ...

  Ecto.Multi.insert(multi, ...)
end
eddy147

eddy147

isn’t update_all only used for updating multiple rows with the same value?

blatyo

blatyo

Conduit Core Team

It can use SQL functions to set different values. Though, if you’re looking to pass data to update, insert_all + the upsert options on_conflict and conflict_target are probably what you want.

eddy147

eddy147

I will try with the insert_all function, thx.

For maybe other people, reason I am asking is that I have a list of changesets, that I want to bulk update, not insert.
Ecto.Multi is not suited, because it is for executing multiple statements in a single transaction.
update_all/3 Is not suited because it is for updating multiple rows with the same value.
So I am a bit lost how to do a bulk update for all kinds of differents ids.

For example, how to bulk update this:

[
  %MyStruct{id: 23, distance: 45},
  %MyStruct(id: 46, odometer: 37181}
  .. etc
]

I can not update thm one-by-one, as this is far too much DB IO.

dimitarvp

dimitarvp

What is your problem with that exactly? That’s less DB concurrency and allows you to do more DB operations in parallel.

When you say “X is too much DB I/O”, have you measured it?

— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
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
spammy
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
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
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
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

Other Trending Topics Top

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
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
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
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
ausimian
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

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews