Fuzzy scoping in Rails with PostgreSQL

Updated . Posted . Visible to the public.

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

Writing a fuzzy query in Rails

User.where("similarity(name, ?) > 0.3", "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

Ordering by best match

User
  .where("similarity(name, ?) > 0.3", "John")
  .order(Arel.sql("similarity(name, 'John') DESC"))

Indexing

See Trigram indexing as an alternative to PostgreSQL fulltext search.

Julian
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Julian to makandra dev (2025-04-14 07:00)