Search code examples
postgresqlelixirecto

Repeat a where clause statement for an Ecto query based on a list


I'm trying to create a search query using Ecto/postgres. Here's the first part of my query:

query = from l in Log,
  join: u in assoc(l, :user),
  where: u.id == ^current_user.id,
  select: l

The user can type in any number of terms (separated by white space) into a text box and then these terms are used to filter the result set. I'm using String.split to transform the original string into a set of where clauses (AND'd together) that are appended to the query:

search_term
|> String.split()
|> Enum.map( fn(term) ->
  query = from l in query,
    where: fragment("comment ~* ?", ^term)
end)

Except that this statement has no effect. I'm assuming that the query assignment only lives within the scope of the function. My mind is clouded by imperative thinking. How do I achieve this in a functional manner?


Solution

  • I'm assuming that the query assignment only lives within the scope of the function.

    Yes, exactly.

    You should use Enum.reduce for this, and pass the original query as the initial value of the accumulator:

    search_term
    |> String.split()
    |> Enum.reduce(query, fn(term, query) ->
      from l in query, where: fragment("comment ~* ?", ^term)
    end)