Filter: Could not cast function arguments for trigram_similarity/2

I have an action that filters by trigram similarity:

  read :search_name do
    argument :name, :string, allow_nil?: false

    prepare fn query, _ ->
      query
      |> Ash.Query.filter(
        expr(trigram_similarity(first_name <> " " <> last_name, ^arg(:name)) > 0.5)
      )

    end
  end

Calling the action from iex results in:

...
 %Ash.Error.Unknown.UnknownError{
         error: "filter: Could not cast function arguments for trigram_similarity/2",
...

Everything works as expected if I change the action to:

...
      expr(trigram_similarity(first_name <> " " <> last_name, "hardcoded string") > 0.5)
...

I’m using a prepare block because I also want to sort by trigram similarity and I’m attempting to port over the approach that was recommended to me for, and is currently working for, geometric distance, which involves a prepare and a calculation. But before I get to the sorting part, the filtering part of the prepare gives me this error.

So it seems that I’m doing something wrong with regards to the argument, and I’m trying to figure out what that is… Something to do with the type? I anticipated running into some confusion there when doing sorting, but filtering works when I use a hardcoded string, so I’m not exactly certain what I should be coercing the argument into.

Or have I gone down the wrong path entirely here with this approach?

Thanks.

Nice to see an Ash section on the forums :slight_smile:

the ^arg(:name) construction is only necessary in “templates”, i.e

# This is statically set on the DSL
read :read do
  filter expr(trigram_similarity(first_name <> " " <> last_name, ^arg(:name)) > 0.5)
end

Adding filters in preparations its no longer a template. What you’re looking for is something like this:

prepare fn query, _ ->
  query
  |> Ash.Query.filter(
    expr(trigram_similarity(first_name <> " " <> last_name, ^query.arguments.name) > 0.5)
  )

end
1 Like

:person_facepalming: I had this staring me in the face from the sorting example too.

Everything is working flawlessly.

THANK YOU.

1 Like