Search code examples
elixirecto

How can I create an Ecto.Query to get the length of an array of my schema's fields?


I have this schema and empty query:

defmodule User.User do
 use Ecto.Schema

 schema "people" do
     field(:name, :string)
     field(:jobs, {:array, :string})
     field(:devices, {:array, :string})
   end

 def count_user_structs() do
  ...
 end
end

and this is the result in console:

[
  %User.User{
    __meta__: #Ecto.Schema.Metadata<:loaded, "people">,
    devices: ["MacBook Air", "MacBook Pro"],
    id: 1,
    jobs: ["Frontend Developer", "Backend Developer", "Software Developer"],
    name: "Dmitri"
  }
]

How can I create an Ecto.Query to get the length of an arrays(jobs and devices)?


Solution

  • Assuming you are using PostgreSQL, the length of the array field could be calculated with coalesce(array_length(field, 1), 0).

    In we have fragment/1.

    That said, somewhat alongside below should work

    from u in User, 
        select: %{jobs: fragment("coalesce(array_length(jobs, 1), 0)")}