`Enum.map(n, fn -> %{….} end)` is not a valid query expression. If you want to invoke Enum.map/2 in a query, make sure that the module Enum is required and that map/2 is a macro

Hey guys, so I’m in need of help understanding how can I use Enum.map in my query. I’m doing some DB querying and pagination and all works fine, but I’ll need to do more clear data representation and I have a JSONB field in my DB which I need to break down.

My goal is to do something like this

def google_news_query(google_news_scope) do
    from n in google_news_scope,
    select: %{
      news: Enum.map(n.news, fn n -> %{
        relevance_score: n.relevance_score
      }
    end
    )}
  end

But I guess I can’t because of

(Ecto.Query.CompileError) Enum.map(n.news, fn n -> %{relevance_score: n.relevance_score} end) is not a valid query expression. If you want to invoke Enum.map/2 in a query, make sure that the module Enum is required and that map/2 is a macro

Is this achievable? How can I create a macro that can help me do additional Enum over the queried data?

You can’t. Either create a subquery to do at the database level what you want, or retrieve raw data and do the map on your application.

4 Likes

Yup noted, I just figure out where I can Enum on raw data after the query, need to play a bit longer. I was just trying to see is it even possible to do it like this, nevertheless thanks.

@Copser you can also take a look a postgresql documentation for better ways to manipulate the JSONB field. You will find a way to achieve the result you want.

2 Likes

hey @Tee thanks, like @LostKobrakai suggested I’ve ended up getting my data after the query :grinning: