sabri
Hello,
I have found lovely CSV library that I will be using to insert CSV files into postgres.
But there are some issues I am wondering about, as I am fresh in elixir.
Ok, here is the sample code I will be using to insert the CSV into DB:
File.stream!("ignore/customers.csv")
|> CSV.decode
|> Enum.each(fn
{:ok, [id, nm, csr, sal]} ->
Customer.changeset(%Customer{},
%{masterid: id,
custname: nm,
csrid: String.to_integer(csr),
salesid: String.to_integer(sal)})
|> Repo.insert
{:error, message} ->
# Whatever you want to do with invalid rows
end)
My questions are:
-
In the
Enum.eachwhat is the time interval between each call to theRepo.insert? can I control this to make sure that my DB won’t get over-pumped with queries? -
As I need to implement a progress bar in the browser while the CSV being inserted into DB, Can I broadcast a progress message in successful
Enum.eachto client using channels? for ex: after|> Repo.insertto broadcast message as:
MyApp.Endpoint.broadcast client_topic, “progress”, %{
progress: progress_number
}
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
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
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
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
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
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
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted”
Version...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hobbes is a low-level distributed database for the Elixir programming language.
Hobbes provides a simple, safe, and scalable storage lay...
New
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
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
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
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #blog-post
- #ai
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
minhajuddin
If you have a lot of records and don’t need data validation use
COPYto pipe the data to postgres. This is very fast.The time between each insert is actually the time it takes to insert the record, So you insert a record and then another. So you probably don’t have to worry about overloading the server. Also, broadcasting a message should also be possible using the technique you mention
sabri
Thank you, it’s there an example of using copy? Then I think I won’t be able to broadcast progress messages?
In general, no more than 25000 record expected in the CSV file
minhajuddin
COPY ... TO stdout docs example throws errors · Issue #228 · elixir-ecto/postgrex · GitHub I would definitely use COPY for that volume
sabri
Yea, if I need one second for each individual row to insert, it would take hours to complete..
So, as for the link provided, how would I refactor their example below, so that it will be feeded by the CSV.decode in my code above?
But, then, I will lose validation as you mentioned? any work arround for possible errors to handle?
Thanks for valuable help!
hq1
I recently faced a similar task, so hopefully some of my experiences will come in handy.
COPYwas my first thought. It’s the most efficient way to import CSV data to postgres, period.It’s also the least flexible way from an Elixir app perspective. Building a custom query, handling separators, error handling/reporting, testing, finally “all or nothing” semantics (it’s a single transaction).
If you’re OK with the above,
COPYis for you.If you’re troubled with performance and still don’t want to completely sacrifice flexibility, consider using nimble_csv. Thanks to super clever implementation (metaprogramming and binary matching), sequential parsing is way faster than the library you’ve mentioned, that attempts parsing in parrallel (IIRC 5M rows in 20 seconds vs 2 minutes according to my microbenchmarks).
nibmble_csvworks with Streams too, so you’ll be fine when it comes to memory spikes.If you care about parallel processing later on, to make the DB insertion efficient (by utilizing the connection pool and bulk inserts), here’s what you can do to make it reasonably fast:
process_in_parallelimplementation is entirely up to you. If you’re on Elixir 1.4, you may useasync_stream; if lower than that,parallel_streamlooks like an OK choice. Just make sure the number of parallel processes is somewhat in line withSystem.schedulers_onlineand your database pool size. Make it configurable, measure, rinse and repeat. How scheduling works.Your
chunk_handler_fn/1will receive.. a chunk of 1000 decoded rows. You may prepare changesets there, have them validated, filter the chunk based onvalid?property, remap the columns according to a custom mapping rule, build a list of maps to be inserted (changeset.changesis already there for you, perhaps needs to be enriched a little) and push it throughRepo.insert_allin each individual process.Caveats:
on_conflictoption if the need be to perform an upsert/ignore constraint errors.Stream.with_index. Note, that you will have to calculate the offset based on the header presence (the very first row gets either skipped or included).nimble_csvwill brutally crash on bad rows, e.g. discontinued quote. You might want to rescue from (catch)NimbleCSV.ParseErrorand convert it to something useful ({:error, {:parse_error, reason}}tuple most likely).Hope this helps.
Cheers
edit added a note about
NimbleCSV.ParseErrorhandling, fixed grammerjosevalim
Great answer! From the earlier example, I would definitely use
Repo.insert_all. Also the parallel processing can be done with Task.async_stream from Elixir v1.4.sabri
Thanks for detailed answer, I will try to do the best thing I can now
sabri
Ok, here is my humble try with a CSV file that has 100 entry like:
CSV:
Code:
But,
chunk_handler_fnwas never called, I have attached the simple100.csvsample file here:https://s3.eu-central-1.amazonaws.com/test-files-74/100.csv
Is there something I have missed?
michalmuskala
Task.async_streamreturns a lazy stream - it won’t be executed unless you consume it. This can be done withStream.runif you don’t care for results or any of the functions working on enumerables in an eager way if you do care about return values (most notably from theEnummodule).sabri
I do care about results, so I am not using
Enum, in-fact, I will be broadcasting results to the client, to implement a progress bar of achievement of the task, as in the top of this thread.If I run the stream as
Stream.runwill it run all the chunks until the stream is all streamed? or shall I run it for each chunk?When will the temp streamed uploaded file get deleted? after finishing the stream?