loading...

Elixir - csv import

ideamarcos profile image Marcøs ・1 min read

See Files on Github
country-codes.csv
create_country_table.exs

This post expands on this article from 'Experimenting with Code' to only import a subset of csv columns into Postgres using Ecto.

In this case, we are only concerned with the code and name columns from country-codes.csv. This example uses File.stream() and CSV.decode!() to get just the two columns and pass it to the COPY command.

file_path
|> File.stream!()
|> CSV.decode!(headers: true)
|> Stream.map(fn row ->
  [
    row["code"],
    row["name"]
  ]
end)
|> CSV.encode()
|> Enum.into(stream)
Enter fullscreen mode Exit fullscreen mode

Discussion

pic
Editor guide