How to optimize this Ecto query?

query = case is_nil(user_id) do
  true ->
    from pv in __MODULE__,
      where: pv.day == ^today,
      where: pv.article_id == ^article_id,
      where: pv.ip == ^ip_address,
      where: is_nil(pv.user_id)
  false ->
    from pv in __MODULE__,
      where: pv.day == ^today,
      where: pv.article_id == ^article_id,
      where: pv.ip == ^ip_address,
      where: pv.user_id == ^user_id
end

Here is one way:

query =
  from __MODULE__, where: [day: ^today, article_id: ^article_id, ip: ^ip_address]
if user_id do
  from pv in query, where: pv.user_id == ^user_id
else
  from pv in query, where: is_nil(pv.user_id)
end

I would likely break that in two separate functions.

5 Likes

Cool! Thanks!

:grimacing: