pg_trgm
text similarity measurement and index searching based on trigrams
Overview
| Package | Version | Category | License | Language |
|---|---|---|---|---|
pg_trgm | 1.6 | FTS | PostgreSQL | C |
| ID | Extension | Bin | Lib | Load | Create | Trust | Reloc | Schema |
|---|---|---|---|---|---|---|---|---|
| 2390 | pg_trgm | No | Yes | No | Yes | Yes | No | - |
Version
| PG18 | PG17 | PG16 | PG15 | PG14 |
|---|---|---|---|---|
| 1.6 | 1.6 | 1.6 | 1.6 | 1.6 |
Install
Note: This is a built-in contrib extension of PostgreSQL
Usage
pg_trgm: Text similarity measurement and index searching based on trigrams
The pg_trgm module provides functions and operators for determining the similarity of alphanumeric text based on trigram matching, plus index operator classes for fast string similarity searches.
A trigram is a group of three consecutive characters from a string. Two strings are similar if they share many trigrams.
Functions
| Function | Description |
|---|---|
similarity(text, text) → real | Returns similarity between 0 and 1 |
show_trgm(text) → text[] | Returns array of all trigrams in the string |
word_similarity(text, text) → real | Similarity of first string to most similar word in second |
strict_word_similarity(text, text) → real | Similar but with stricter word boundary matching |
show_limit() → real | (Deprecated) Returns pg_trgm.similarity_threshold |
set_limit(real) → real | (Deprecated) Sets pg_trgm.similarity_threshold |
Operators
| Operator | Description |
|---|---|
text % text → boolean | True if similarity > pg_trgm.similarity_threshold |
text <% text → boolean | True if word similarity > pg_trgm.word_similarity_threshold |
text %> text → boolean | Commutator of <% |
text <<% text → boolean | True if strict word similarity > threshold |
text %>> text → boolean | Commutator of <<% |
text <-> text → real | Distance (1 - similarity) |
text <<-> text → real | Word distance (1 - word_similarity) |
text <->> text → real | Commutator of <<-> |
text <<<-> text → real | Strict word distance |
text <->>> text → real | Commutator of <<<-> |
GUC Parameters
| Parameter | Default | Description |
|---|---|---|
pg_trgm.similarity_threshold | 0.3 | Threshold for % operator |
pg_trgm.word_similarity_threshold | 0.6 | Threshold for <% and %> operators |
pg_trgm.strict_word_similarity_threshold | 0.5 | Threshold for <<% and %>> operators |
Index Support
GiST and GIN indexes support the similarity operators:
Text Search Example
Using trigram indexes to speed up LIKE / ILIKE / regex queries:
GIN and GiST trigram indexes also accelerate LIKE, ILIKE, ~, and ~* queries automatically.
Was this page helpful?
Thanks—your feedback helps us improve this page.
What got in the way? (optional)