Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto query - order_by field in jsonb column

Tags:

elixir

ecto

The following code works fine when ordering an Ecto query by the created_at column.

sort_params = [asc: :created_at]
query = from user in users,
      order_by: ^sort_params,
      limit: ^page_size,
      offset: ^offset

Assuming I have a database column of type jsonb called info, and one of the fields in the JSON object is "status", is there a way to sort by that field? Does Ecto have a valid equivalent to something like

sort_params = [asc: :info.status]

like image 610
AJP Avatar asked Sep 03 '25 15:09

AJP


1 Answers

Yes,

You can use Ecto.Query.API.fragment/1 for that.

# you can use fragment/1 only directly in the query

query = from user in users,
  order_by: fragment("info->>'status' ASC"),
  limit: ^page_size,
  offset: ^offset
like image 125
PatNowak Avatar answered Sep 05 '25 16:09

PatNowak