defmodule Moldb.Search do import Ecto.Query, warn: false alias Moldb.Repo alias…
- User
defmodule Moldb.Search do import Ecto.Query, warn: false alias Moldb.Repo alias Moldb.Compounds.{Compound, Substance}
def search(query) do compounds = search_compounds(query) substances = search_substances(query) compounds ++ substances end
def search_compounds_and_substances(query) do Task.async_stream([&search_compounds/1, &search_substances/1], fn f -> f.(query) end) |> Enum.reduce([], fn {:ok, results}, acc -> acc ++ results end) end
defp search_compounds(query) do Repo.all( from(c in Compound, where: ilike(c.iupac_name, ^"%#{query}%"), select: {c.iupac_name, "Compound"} ) ) end
defp search_substances(query) do Repo.all( from(s in Substance, where: ilike(s.substance_name, ^"%#{query}%"), select: {s.substance_name, "Substance"} ) ) end end Analyze the code, rewrite it to most efficient, high performance alternative.
- Assistant
To improve the performance of your code, you can make the following optimizations:
-
Run the searches concurrently: Use
Task.asyncandTask.awaitto runsearch_compoundsandsearch_substancesin parallel. This takes advantage of Elixir's concurrency features to perform I/O-bound operations simultaneously, reducing overall execution time. -
: Instead of using with , which can be inefficient for large lists, use to flatten the results efficiently.
-