Ilike filtering, show more relevant result

Hey there,

I am trying to filter a table by the title property, here is my current filter:

def by_title(query, title) do
    title_flex = "%#{WordSmith.remove_accents(title)}%"

    from(e in query,
      where: ilike(fragment("lower(unaccent(?))", e.title), ^title_flex)
    )
  end

it is really simple, this returns everything that has the sent title param in it as expected.

How could I make this order the query by returning the items that start with the param first?

I know I could remove the % from the start of the title, but then it would only return the ones that start with the title exactly, but I just want to have those first with the ones that don’t start later.
I want the more relevant ones first.

Any tips?

Thanks!

I have used this in Rails and not Ecto but I think you might want something like:

1 Like

I ended up doing this:

def by_title(query, title) do
    title_flex = "%#{WordSmith.remove_accents(title)}%"
    title = "#{WordSmith.remove_accents(title)}%"

    from(e in query,
      where: ilike(fragment("lower(unaccent(?))", e.title), ^title_flex),
      order_by: [desc: ilike(fragment("lower(unaccent(?))", e.title), ^title)]
    )
  end