Skip to main content
Version: Latest - 1.0.0-alpha.38

pg_trgm

pg_trgm compares text by splitting it into trigrams. Durcno exposes its similarity scores and predicates as typed expressions, so they work in select, where, and orderBy without raw SQL.

Prerequisites​

Enable the extension in a migration:

CREATE EXTENSION IF NOT EXISTS pg_trgm;

pg_trgm is a PostgreSQL contrib extension and needs no extra column type. It works with the built-in text and varchar columns.

Import​

import {
showTrgm,
similar,
similarity,
strictWordSimilar,
strictWordSimilarity,
wordSimilar,
wordSimilarity,
} from "durcno";

Indexing​

Use a GIN index with the gin_trgm_ops operator class:

import { index, notNull, pk, table, text } from "durcno";

export const Articles = table(
"public",
"articles",
{
id: pk(),
title: text({ notNull }),
},
{
indexes: (t) => [index([t.title.opclass("gin_trgm_ops")]).using("gin")],
},
);

Querying​

Scores are useful for ranking; predicates filter by the session's similarity thresholds:

import { desc, similar, similarity } from "durcno";

const term = "postgres full text";

const results = await db
.from(Articles)
.select(() => ({
id: Articles.id,
score: similarity(Articles.title, term),
}))
.where(() => similar(Articles.title, term))
.orderBy(() => desc(similarity(Articles.title, term)));

See Trigram Similarity Functions and Trigram Similarity predicates for the full API.