rent
PostgreSQL extensions

pg_trgm

What it is

pg_trgm is a PostgreSQL-supplied extension that compares text by shared three-character groups. It supports similarity scoring and indexed fuzzy matching without introducing a separate search system.

What it provides

  • Text similarity scores and threshold-based matching
  • Fast indexed LIKE, ILIKE, regular-expression, and similarity searches
  • GiST and GIN operator classes for text columns

Use it for typo-tolerant name lookup, autocomplete, deduplication, fuzzy product search, or suggesting a likely match after a misspelling.

Use it with Rent

extension pg_trgm {
  name = "pg_trgm"
}

The RSL declaration makes installation and migration intent part of the reviewed application schema. Register the typed pack at runtime to call its APIs:

let trgm = extensions.register_pack::<PgTrgm>()?;
let matches = trgm.similar_to(
    user::name(),
    "Lovelace",
);

let score = trgm.similarity_to(
    user::name(),
    "Lovelace",
);

let users = client
    .user()
    .where_raw(matches)
    .order_by_expression_desc(score)
    .all()
    .await?;

Run the application

cargo run -p rent --example extension_08_pg_trgm

Set DATABASE_URL to a disposable PostgreSQL server whose role can create databases and install pg_trgm. The application creates an isolated database and two users, then finds Grace Hopper from the misspelling Grace Hoper through the generated client. It checks the similarity score and a search with no matches. The extension is installed in a custom schema, and the temporary database is removed afterward.

similar_to uses PostgreSQL's session similarity threshold. Tune that threshold and add a GIN or GiST trigram index for your workload; a similarity predicate alone does not create an index. Its standalone extension declaration is crates/rent/examples/extension_08_pg_trgm/schema.rsl.

On this page