Casting to certain types on schemaless queries

I will answer my own question and post it here for someone else help when needed

I have a Decimal field in my database and Ecto selects as Decimal type upon retrival.

Decimal is very annoying, to sum up, or do any aggregate, stream operations because of the need for calling Decimal. functions.

Rather than iterating over the results to cast yourself, simply tell Ecto to select the desired type with:

from p in Post, select: type(avg(p.cost), :float)
from p in Post, select: type(filter(avg(p.cost), p.cost > 0), :integer)

more details:

https://hexdocs.pm/ecto/Ecto.Query.API.html#type/2

1 Like