Sub topic 6
Operator classes: matching an index to your operators
Prerequisites and the matching problem
This chapter assumes you can write basic SELECT queries and create PostgreSQL indexes. You should also know common operators such as =, <, LIKE, @>, and @@.
An operator class is a set of rules that tells an index method how to store a data type and which operators the index can support. The data type alone does not determine whether an index can answer a query. The operator matters too.
For example, a B-tree index on text supports equality and ordering. It may not efficiently support every kind of text pattern search. A different operator class can change the comparison rules so that the same B-tree structure supports a different query shape.
The planner can use an index only when the query's expression and operator match what the index's operator class provides.
Default operator classes
Each index method has default operator classes for many PostgreSQL data types. When you write a simple index, PostgreSQL usually selects the default:
CREATE INDEX people_name_idx
ON people (name);For a B-tree index on text, the default class supports comparisons such as:
=<,<=,>, and>=ORDER BY- left-anchored pattern searches in situations where the collation permits them
The database collation affects text ordering. Under the C locale, ordinary byte ordering makes prefix matching straightforward. Under many other locales, linguistic sorting rules mean that a normal B-tree index might not support LIKE 'prefix%' efficiently.
You can choose a non-default operator class when the default does not match the query:
CREATE TABLE people (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
CREATE INDEX people_name_pattern_idx
ON people (name text_pattern_ops);
SELECT id, name
FROM people
WHERE name LIKE 'Ann%';text_pattern_ops gives the B-tree pattern-comparison behavior needed for left-anchored LIKE searches. The pattern must begin with fixed characters. A pattern such as '%ann%' has no fixed starting point, so this B-tree index generally cannot jump directly to the matching rows.
The operator class does not change the column's data type or the result of the comparison. It changes how the index organizes values for supported operations.
Trigram operator classes
For substring searches, use the pg_trgm extension. It breaks text into overlapping groups of three characters called trigrams. A GIN or GiST index using gin_trgm_ops or gist_trgm_ops can then find text containing a pattern.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX people_name_trgm_idx
ON people USING gin (name gin_trgm_ops);
SELECT id, name
FROM people
WHERE name ILIKE '%smith%';gin_trgm_ops is a non-default operator class for the GIN index method. It supports searches involving LIKE, ILIKE, and regular expressions when the pattern contains useful trigrams. It is a better match than a B-tree for arbitrary substrings such as '%smith%'.
Very short patterns may produce few or no useful trigrams. The planner can therefore choose a sequential scan even when the trigram index exists. That choice is normal: an index is an access method, not a command that the planner must always use.
A trigram index also consumes more space and adds work to writes. Create one when substring or similarity searches are an important part of the workload.
Operator classes and expression matching
The indexed expression must match the query expression. For example, an index on lower(email) supports a query that applies lower to the column:
CREATE INDEX users_lower_email_idx
ON users (lower(email));
SELECT id
FROM users
WHERE lower(email) = '[email protected]';An index on the plain email column does not automatically support that expression. Similarly, an index using text_pattern_ops does not turn ILIKE into a prefix search, and it does not replace a trigram index for arbitrary substrings.
Inspecting available classes
PostgreSQL exposes operator classes in catalog views:
SELECT index_method, opcname, opcintype::regtype AS data_type, opcdefault
FROM pg_opclass
WHERE opcname IN ('text_pattern_ops', 'gin_trgm_ops', 'gist_trgm_ops')
ORDER BY index_method, opcname;The opcdefault column shows whether a class is the default for its data type and index method. An operator class belongs to an index method such as B-tree, GIN, or GiST. The method supplies the general index structure; the class supplies type-specific behavior.
> callout note > Choose an operator class from the query operators backward. Start with the operation you need, such as prefix matching, substring matching, JSON containment, or range overlap. Then select an index method and operator class that explicitly support it.
A practical decision process
When an index is not helping, check these questions:
- Does the index method support the operator?
- Does the operator class support that operator for this data type?
- Does the indexed expression exactly match the query expression?
- Does collation affect text ordering or pattern matching?
- Does the planner estimate that the index is cheaper than a sequential scan?
Use EXPLAIN to verify the result rather than inferring it from the index definition.
EXPLAIN (COSTS OFF)
SELECT id
FROM people
WHERE name ILIKE '%smith%';An index scan or bitmap index scan indicates that the planner found a usable path. A sequential scan may still be correct when the table is small or the predicate matches many rows.
Exercise
Which operator class is a suitable choice for a text column queried with ILIKE '%lake%': text_pattern_ops on a B-tree or gin_trgm_ops on a GIN index? Why?
Show answer
Use gin_trgm_ops on a GIN index because the query searches for an arbitrary substring. text_pattern_ops is intended for left-anchored B-tree patterns such as LIKE 'lake%'.