pg_trgm GIN Index For Infix LIKE

Index infix LIKE searches with the pg_trgm extension: a GIN index on gin_trgm_ops serves %son% patterns and similarity ordering that a plain btree cannot.

SqlData Fetching

Code

snippet
-- 前缀 LIKE 能走 btree(text_pattern_ops),但中缀(infix)匹配 %son% 没有索引可用;
-- pg_trgm 把文本切成三元组,GIN 索引让任意位置的模糊匹配都能走索引
CREATE EXTENSION IF NOT EXISTS pg_trgm;

CREATE TABLE products (
    id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL
);

CREATE INDEX products_name_trgm ON products USING gin (name gin_trgm_ops);

SELECT id, name
FROM products
WHERE name LIKE '%son%';

-- 相似度检索同样受益:% 按 pg_trgm.similarity_threshold 过滤,similarity 打分
SELECT name, similarity(name, 'jackson') AS sim
FROM products
WHERE name % 'jackson'
ORDER BY sim DESC;

What the code does

Several statements share this file — SELECT / CREATE, with products among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Run it in the products database context.

Statements that matter

SELECT name, similarity(name, 'jackson') AS sim
FROM products
WHERE name % 'jackson'
ORDER BY sim DESC;
SELECT id, name
FROM products
WHERE name LIKE '%son%';
CREATE TABLE products (
id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`products`.