Search code examples
postgresqlelixirphoenix-frameworkecto

How to full text search more than one "model" field using Ecto and PostgreSQL


I'm using this search function in my controller:

def search(query, search_term) do
    (from u in query,
    where: fragment("to_tsvector(?) @@ plainto_tsquery(?)", u.name, ^search_term),
    order_by: fragment("ts_rank(to_tsvector(?), plainto_tsquery(?)) DESC", u.name, ^search_term))
  end

It's working for just one field of my model. I would like to search all fields or be able to search a selected few (name_label, contacts, ...) at the same time. How to do it?


Solution

  • You can use

    (to_tsvector(col1) || to_tsvector(col2))) @@ plainto_tsquery(?)
    

    to concatenate text search vectors.