Fuzzy search in Rails with PostgreSQL

Posted . Visible to the public.

When you want to search for records in a model where a string column roughly matches a given term, you can use PostgreSQL’s trigram similarity search.

Write a fuzzy query in Rails

User.where("similarity(name, ?) > 0.4", "John")

This finds all users where the name is similar to "John" with a similarity score above 0.3.

You can tune the threshold:

  • Closer to 1.0 = stricter match
  • Closer to 0.0 = looser match

Order by best match

User
  .where("similarity(name, ?) > 0.3", "John")
  .order(Arel.sql("similarity(name, 'John') DESC"))
Julian
License
Source code in this card is licensed under the MIT License.
Posted by Julian to makandra dev (2025-04-14 07:00)