NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / RASTERIZEDDB SERVER / FULL-TEXT SEARCH AND COLLATIONS

Full-text search and collations

Use full-text search to find rows whose text contains words, in any inflected form ("running" finds "runs"), with PostgreSQL's to_tsvector, to_tsquery and @@. Use a case-insensitive collation when 'Bob' and 'bob' must be the same value for comparisons, sorting, unique keys and indexes.

Searching a text column

A search compares a document, reduced by to_tsvector to its normalised words (lexemes), with a query, built by one of the to_tsquery functions.

sql
CREATE TABLE articles (
  id    bigint PRIMARY KEY,
  title text,
  body  text
);

INSERT INTO articles VALUES
  (1, 'Foxes', 'The quick brown fox jumps'),
  (2, 'Dogs',  'Lazy dogs sleep all day'),
  (3, NULL,    'Foxes are quick');

SELECT id FROM articles
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'fox')
ORDER BY id;
text
 id
----
  1
  3

Both sides are normalised the same way: lowercased, stop words dropped, and stemmed under english, so the query fox finds "fox" and "Foxes". You can see what a document and a query become:

sql
SELECT to_tsvector('english', 'The quick brown fox jumps');
SELECT to_tsquery('english', 'urgent & !fragile');
text
'brown':3 'fox':4 'jump':5 'quick':2
'urgent' & !'fragil'

To search several columns as one document, join them with a space and guard the NULLs:

sql
SELECT id FROM articles
WHERE to_tsvector('english', coalesce(title, '') || ' ' || coalesce(body, '')) @@ plainto_tsquery('english', 'quick fox');

The @@ forms

ExpressionMeans
to_tsvector(…) @@ to_tsquery(…)the document matches the query
to_tsquery(…) @@ to_tsvector(…)the same, operands swapped
body @@ to_tsquery('fox')to_tsvector(body) @@ to_tsquery('fox')
body @@ 'quick fox'to_tsvector(body) @@ plainto_tsquery('quick fox'): the right side is plain words, not query syntax

@@ can be used in WHERE, under NOT, combined with other conditions, and in the select list, where it returns a boolean.

Query functions

FunctionReads its text as
to_tsquery([config,] query)query syntax (below)
plainto_tsquery([config,] text)plain words, all required: 'The Quick foxes' is 'quick' & 'fox'
phraseto_tsquery([config,] text)the words as a phrase, in order: 'quick the brown fox' is 'quick' <2> 'brown' <-> 'fox'
websearch_to_tsquery([config,] text)search-box syntax: words are required, "quoted words" are a phrase, or between two parts is either, a leading - excludes: '"quick brown" or lazy -dogs' is 'quick' <-> 'brown' | 'lazi' & !'dog'
to_tsvector([config,] document)the document's lexemes with their positions

Query syntax for to_tsquery:

SyntaxMeaning
a & bboth
a | beither
!anot
a <-> bb directly follows a
a <N> bb is N positions after a
qui:*any lexeme starting with qui
( … )grouping
'two words'a quoted operand; several words in quotes are a phrase

A malformed query (an operator with nothing to apply to, unbalanced parentheses) is an error, not an empty result. A query made only of stop words (to_tsquery('english', 'the')) matches nothing.

Configurations

ConfigurationDoes
englishlowercases, drops PostgreSQL's English stop words, and stems with the Snowball English stemmer that PostgreSQL's english uses
simplelowercases only; no stemming and no stop words

The one-argument forms (to_tsvector(body), to_tsquery('fox')) use english, which is PostgreSQL's default default_text_search_config for English and C locales. Any other configuration name is accepted and treated as english.

sql
SELECT to_tsvector('simple', 'The Fox and the hound');
text
'and':3 'fox':2 'hound':5 'the':1,4

Ranking results

ts_rank scores how well a document matches, computed as PostgreSQL computes it:

sql
SELECT id, ts_rank(to_tsvector('english', body), to_tsquery('english', 'fox')) AS rank
FROM articles
WHERE to_tsvector('english', body) @@ to_tsquery('english', 'fox')
ORDER BY rank DESC, id;
FormArguments
ts_rank(vector, query)
ts_rank(vector, query, normalization)normalization is PostgreSQL's bit mask (0 default, 1, 2, 4, 8, 16, 32, combined with |)
ts_rank(weights, vector, query [, normalization])weights is a four-element array such as '{0.1,0.2,0.4,1.0}' (classes D, C, B, A), each between 0 and 1

The vector argument must be a to_tsvector(…) call.

Full-text indexes

Without an index, a search reads every row. A GIN index over the same to_tsvector expression lets the search read only the rows that hold the query's words:

sql
CREATE INDEX articles_body_fts ON articles USING gin (to_tsvector('english', body));

CREATE INDEX articles_all_fts ON articles
  USING gin (to_tsvector('english', coalesce(title, '') || ' ' || coalesce(body, '')));

A query uses the index when it applies to_tsvector with the same configuration to any of the indexed columns, matched with @@ against a query:

sql
SELECT id FROM articles
WHERE to_tsvector('english', coalesce(title, '') || ' ' || coalesce(body, '')) @@ to_tsquery('english', 'quick & fox');

What an index expression may hold:

  • The configuration is required and must be a literal ('english' or 'english'::regconfig). The one-argument to_tsvector(body) is refused ("functions in index expression must be marked IMMUTABLE"), as in PostgreSQL.
  • The document is one text column, or up to 16 columns joined by || with a separator literal between each two, such as ' '. Each column may be bare, cast to text, or wrapped in coalesce(column, '').
  • title || body with no separator is refused, because it would glue the last word of one column to the first word of the next.
  • An unnamed index is named as PostgreSQL names it, for example articles_to_tsvector_idx.

The index narrows &, | and phrase queries by their words. A query that is only a negation (!fox) or only a prefix (qui:*) cannot be narrowed, and the table is read; inside a larger query (fox & !dog) the other words still narrow it. An index never changes an answer: inserts, updates, deletes, VACUUM and restarts keep it current. pg_indexes shows its definition as PostgreSQL prints it. See Indexes for checking index use and DROP INDEX.

MySQL MATCH … AGAINST and SQL Server CONTAINS

The MySQL and SQL Server front ends translate their full-text syntax onto the same engine: a MySQL FULLTEXT key or MATCH (…) AGAINST (…), and SQL Server's CREATE FULLTEXT INDEX, CONTAINS, FREETEXT, CONTAINSTABLE and FREETEXTTABLE, become GIN indexes and @@ searches. See MySQL and SQL Server for what each front end accepts.

Collations

Text compares by its bytes, which is PostgreSQL's C collation. A column can instead use a case-insensitive, or case- and accent-insensitive, collation.

Declaring a collation

Name the collation after the column's type in CREATE TABLE, or use the type citext:

sql
CREATE TABLE people (
  id    int PRIMARY KEY,
  name  text COLLATE rdb_ci NOT NULL UNIQUE,
  email citext,
  place text COLLATE rdb_ci_ai
);

INSERT INTO people VALUES
  (1, 'Bob', 'Bob@Example.com', 'Café'),
  (2, 'ann', 'ann@x.org', 'Zürich'),
  (3, 'Ännchen', NULL, 'cafe');

SELECT id FROM people WHERE name = 'BOB';                -- 1
SELECT id FROM people WHERE email = 'BOB@example.COM';   -- 1
SELECT id FROM people WHERE place = 'CAFE';              -- 1 and 3
CollationIgnoresOther accepted names
rdb_cicasecase_insensitive, "und-u-ks-level2", "und-x-icu-ks-level2"
rdb_ci_aicase and accentsignore_accents, "und-u-ks-level1", "und-x-icu-ks-level1"
type citextcase
"C", "POSIX", "default", ucs_basic, pg_c_utf8, unicode, and locale names such as "en_US" or "de-DE-x-icu"nothing: compared by bytes

The ICU spellings are the ones PostgreSQL uses for a nondeterministic ICU collation, so a schema written for PostgreSQL with deterministic = false collations keeps its meaning. A value is returned as it was written; only comparisons change. An unknown collation name is refused with 42704, and a collation on a column that is not text with 42804.

A COLLATE in an expression is accepted for the byte-order collations ("C", "POSIX", "default", ucs_basic), which change nothing. Any other collation in an expression is not supported; declare it on the column.

What follows the collation

  • =, <>, <, <=, >, >=, IN (…), BETWEEN, LIKE, ILIKE and IS [NOT] DISTINCT FROM in the WHERE of SELECT, UPDATE and DELETE, against a literal, a parameter or an expression.
  • An uncorrelated IN (SELECT …).
  • UNIQUE, PRIMARY KEY and ON CONFLICT (column): 'abc' and 'ABC' are one key, so inserting the second is a unique violation (23505).
  • CREATE INDEX on the column (B-tree or hash), which then finds what the collation calls equal.
  • ORDER BY the column in a single-table query.
sql
SELECT name FROM people ORDER BY name;

With the names alice, ann, Bob, bobby, Charlie, ZOE and Ännchen in the table, this returns them in that order. The order is by code point of the folded text (lowercased, canonically decomposed, and with accents removed for rdb_ci_ai), not by the Unicode Collation Algorithm, so ZOE sorts before Ännchen. ß is not equal to ss. Values that compare equal come back in a fixed order, by their bytes.

The collation also applies to:

  • comparisons in a join's ON, EXISTS, and correlated IN (SELECT …);
  • GROUP BY (each group shows its least spelling under the collation), SELECT DISTINCT of plain columns, min/max, count(DISTINCT …) and the other DISTINCT aggregates, over one table or a join;
  • UNION, INTERSECT and EXCEPT with the columns named;
  • ORDER BY in any query, and a window's PARTITION BY and ORDER BY;
  • CREATE UNIQUE INDEX, a key added by ALTER TABLE, and a FOREIGN KEY between two such columns with ON DELETE CASCADE, NO ACTION or RESTRICT;
  • ALTER TABLE … ADD COLUMN c text COLLATE rdb_ci (existing rows get their keys) and ALTER COLUMN c TYPE another text type;
  • text made from such a column and compared in WHERE or a join condition: name || '!', and COALESCE, NULLIF, upper, lower, trim, ltrim, rtrim, btrim, substring, substr, left, right and replace over it (upper(name) = 'bob').

It also adds rdb_guid_order, a collation for uuid columns that sorts them in SQL Server's uniqueidentifier order.

Storage cost

Each column with a nondeterministic collation keeps a hidden copy of its folded value, so it takes about twice the space of a plain text column. The copy never appears in SELECT * and is kept current by every write.

Limits

Full-text search

  • There is no tsvector or tsquery column type. Keep the text in a text column and index the to_tsvector(…) expression.
  • Only the english and simple configurations exist; any other name, such as german, is treated as english without an error.
  • ts_rank_cd, ts_headline and setweight are not available. Positions carry no weight class, so every lexeme counts as class D in ts_rank.
  • The word splitter is simpler than PostgreSQL's parser: it keeps an apostrophe inside a word (don't is one word) and does not also emit the parts of a hyphenated word, so a few documents produce slightly different lexemes from PostgreSQL's.

Collations

On a column with a nondeterministic collation these are refused with 0A000, rather than compared by bytes: UNION/INTERSECT/EXCEPT of SELECT * over such a column (name the columns), a HAVING comparing min/max of one, min/max as a window function, SELECT DISTINCT of such a column beside an expression, a CHECK reading one, a partitioned table with one, a foreign key whose action writes the child's key (SET NULL, SET DEFAULT, ON UPDATE CASCADE), ALTER COLUMN TYPE to a type that is not text, and giving an existing column a collation with ALTER TABLE. Any expression over such a column other than those listed above, and one in a select list (DISTINCT upper(name)), compares by bytes. 1.0.1 and earlier refused far more of these (grouping, DISTINCT, min/max, window functions, set operations, joins, foreign keys) and compared every expression over such a column by bytes.

In every version:

  • A regular expression (~, ~*) or SIMILAR TO over such a column is refused with 0A000, as PostgreSQL refuses it for nondeterministic collations.
  • Comparing two columns with different nondeterministic collations is refused with 42P22.
  • Strings inside json/jsonb documents always compare by bytes.

Related pages: Tables and data types, Querying data, Functions and operators, Indexes, JSON and JSONB, PostgreSQL compatibility.

✓ page rendered in 190 µs axum + tera + htmx · no other javascript