What’s the best way to do bulk inserts with Postgrex?
If I have a list [[1,2],[3,4],[5,6]]
what’s the ideal way to handle it in Postgrex.
1 Like
What have you tried so far? Are you using Ecto or just bare Postgrex? What approach would you take with plain SQL?
@benwilson512 I am using Postgrex.I know with Ecto you can do Repo.insert_all
.I am trying to insert 50,000 records.So, till now I have
1.50000 |> Stream.map(fn(item) -> [item,item * 2] end) |> Stream.chunk(1000,1000,[]) |> Task.async_stream(fn(list) -> list |> Enum.each(fn(record) -> Postgrex.query!(pid, "INSERT INTO mytable(val1,val2) VALUES($1,$2) ", list) end) end)
It works but I am trying to insert multiple values in a single transaction
2 Likes
Wooo, quite a number, I’d probably use the PostgreSQL COPY command.
Some relevant threads:
Hello,
I have some troubles with importing of CSV data.
Here is some snippet:
s1 = "\"47\";\"-17756145\";\"some data\";\"type\";\"17756145\";\"50\";2017-07-27 13:34:28.095734;2017-07-27 13:34:28.095734"
s2 = "\"47\";\"-17756146\";\"some data 2\";\"type\";\"17756145\";\"50\";2017-07-27 13:34:28.095734;2017-07-27 13:34:28.095734"
stream = Ecto.Adapters.SQL.stream(MyRepo, "COPY areas(region_code,code,name,type,parent_code,addr_level,inserted_at,updated_at) FROM STDIN CSV DELIMITER ';' ")
MyRep…
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(cs…
I’m found example of COPY FROM STDIN in postgrex.ex on github:
Postgrex.transaction(pid, fn(conn) ->
query = Postgrex.prepare!(conn, "", "COPY posts FROM STDIN",[copy_data:true])
stream = Postgrex.stream(conn, query, [])
Enum.into(File.stream!("posts"), stream)
end)
How I can convert these example to work with through Repo?
Repo.transaction fn ->
query = "some query"
Ecto.Adapters.SQL.query!(Repo, query, [])
#copy from stdin, how??
end
7 Likes
So Postgrex can insert multiple records, and this is precisely what Ecto is doing. If you use Ecto’s insert_all, it inserts multiple records using single INSERT command like this:
INSERT INTO "table" ("a","b","c") VALUES ($1,$2,$3),($4,$5,$6), ... ,($97,$98,$99) ["A", "B", "C", "A", "B", "C", ... , "A", "B", "C"]
If you are using Postgrex directly, I think you need to assemble that SQL on your own, I don’t think it gives you any shortcuts.
2 Likes