Dynamic filters in Ecto

Here I’m going to show how to utilize dynamic/2 function from Ecto.Query together with pattern matching to build a query with dynamic filters.

Here is the code:

At first we iterate over @filters list and pass each one as the first parameter to filter/3 function. params gets pattern matched so Elixir chooses the definition based on its contents. There we add a condition and keep on reducing.

If everything’s OK then we just build the query passing dynamic to where clause.

If we encounter invalid params (for example I added integer parsing) we return an error and reduce_while/3 halts the work and returns this error.

Finally here’s an example how to use this query in a controller:

Happy quering!