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.
Full-text search
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.
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; id
----
1
3Both 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:
SELECT to_tsvector('english', 'The quick brown fox jumps');
SELECT to_tsquery('english', 'urgent & !fragile');'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:
SELECT id FROM articles
WHERE to_tsvector('english', coalesce(title, '') || ' ' || coalesce(body, '')) @@ plainto_tsquery('english', 'quick fox');The @@ forms
| Expression | Means |
|---|---|
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
| Function | Reads 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:
| Syntax | Meaning |
|---|---|
a & b | both |
a | b | either |
!a | not |
a <-> b | b directly follows a |
a <N> b | b 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
| Configuration | Does |
|---|---|
english | lowercases, drops PostgreSQL's English stop words, and stems with the Snowball English stemmer that PostgreSQL's english uses |
simple | lowercases 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.
SELECT to_tsvector('simple', 'The Fox and the hound');'and':3 'fox':2 'hound':5 'the':1,4Ranking results
ts_rank scores how well a document matches, computed as PostgreSQL computes it:
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;| Form | Arguments |
|---|---|
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:
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:
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-argumentto_tsvector(body)is refused ("functions in index expression must be marked IMMUTABLE"), as in PostgreSQL. - The document is one
textcolumn, or up to 16 columns joined by||with a separator literal between each two, such as' '. Each column may be bare, cast totext, or wrapped incoalesce(column, ''). title || bodywith 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:
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| Collation | Ignores | Other accepted names |
|---|---|---|
rdb_ci | case | case_insensitive, "und-u-ks-level2", "und-x-icu-ks-level2" |
rdb_ci_ai | case and accents | ignore_accents, "und-u-ks-level1", "und-x-icu-ks-level1" |
type citext | case | |
"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,ILIKEandIS [NOT] DISTINCT FROMin theWHEREofSELECT,UPDATEandDELETE, against a literal, a parameter or an expression.- An uncorrelated
IN (SELECT …). UNIQUE,PRIMARY KEYandON CONFLICT (column):'abc'and'ABC'are one key, so inserting the second is a unique violation (23505).CREATE INDEXon the column (B-tree or hash), which then finds what the collation calls equal.ORDER BYthe column in a single-table query.
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 correlatedIN (SELECT …); GROUP BY(each group shows its least spelling under the collation),SELECT DISTINCTof plain columns,min/max,count(DISTINCT …)and the otherDISTINCTaggregates, over one table or a join;UNION,INTERSECTandEXCEPTwith the columns named;ORDER BYin any query, and a window'sPARTITION BYandORDER BY;CREATE UNIQUE INDEX, a key added byALTER TABLE, and aFOREIGN KEYbetween two such columns withON DELETE CASCADE,NO ACTIONorRESTRICT;ALTER TABLE … ADD COLUMN c text COLLATE rdb_ci(existing rows get their keys) andALTER COLUMN c TYPEanother text type;- text made from such a column and compared in
WHEREor a join condition:name || '!', andCOALESCE,NULLIF,upper,lower,trim,ltrim,rtrim,btrim,substring,substr,left,rightandreplaceover 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
tsvectorortsquerycolumn type. Keep the text in atextcolumn and index theto_tsvector(…)expression. - Only the
englishandsimpleconfigurations exist; any other name, such asgerman, is treated asenglishwithout an error. ts_rank_cd,ts_headlineandsetweightare not available. Positions carry no weight class, so every lexeme counts as class D ints_rank.- The word splitter is simpler than PostgreSQL's parser: it keeps an apostrophe inside a word (
don'tis 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 (
~,~*) orSIMILAR TOover such a column is refused with0A000, as PostgreSQL refuses it for nondeterministic collations. - Comparing two columns with different nondeterministic collations is refused with
42P22. - Strings inside
json/jsonbdocuments always compare by bytes.
Related pages: Tables and data types, Querying data, Functions and operators, Indexes, JSON and JSONB, PostgreSQL compatibility.