How to store array with Ecto using Postgres

PostgresqlPhoenix FrameworkEcto

Postgresql Problem Overview


I would like to store an array of floating point values with Ecto using Postgres. I'm using Ecto with the Phoenix Framework and Elixir.

How would I define my model and migration for this?

I haven't tried much, except searching the web, which didn't find anything useful :-(

I did try defining a model with a schema like this:

  schema "my_model" do
    field :my_array, :array

    timestamps
  end

which gave an error "invalid or unknown type :array for field :my_array"

Postgresql Solutions


Solution 1 - Postgresql

I found the answer in the list of primitive types for Ecto.Schema here:

Ecto.Schema

The answer is to define the type like this:

  schema "my_model" do
    field :my_array, {:array, :float}

    timestamps
  end

Solution 2 - Postgresql

As Josh wrote use the array type from Ecto.Schema

In the model:

schema "my_model" do
  field :my_array, {:array, inner_type}
end

@neildaemond Migration:

alter table(:my_models) do
  add :my_array, {:array, inner_type}
end

Replace inner_type with one of the valid types, such as :string.

You can also do the same thing with a map type:

schema "my_model" do
  field :my_map, {:map, inner_type}
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJosh PetittView Question on Stackoverflow
Solution 1 - PostgresqlJosh PetittView Answer on Stackoverflow
Solution 2 - PostgresqlBartek SkwiraView Answer on Stackoverflow