9.13. Функции и операторы текстового поиска

В Таблице 9.42, Таблице 9.43 и Таблице 9.44 собраны все существующие функции и операторы, предназначенные для полнотекстового поиска. Во всех деталях возможности полнотекстового поиска в Postgres Pro описаны в Главе 12.

Таблица 9.42. Операторы текстового поиска

Оператор

Описание

Пример(ы)

tsvector @@ tsqueryboolean

tsquery @@ tsvectorboolean

Аргумент tsvector соответствует аргументу tsquery? (Аргументы могут передаваться в любом порядке.)

to_tsvector('fat cats ate rats') @@ to_tsquery('cat & rat')t

text @@ tsqueryboolean

Переданная текстовая строка, неявно преобразованная функцией to_tsvector(), соответствует tsquery?

'fat cats ate rats' @@ to_tsquery('cat & rat')t

tsvector @@@ tsqueryboolean

tsquery @@@ tsvectorboolean

Это устаревший синоним для @@.

to_tsvector('fat cats ate rats') @@@ to_tsquery('cat & rat')t

tsvector || tsvectortsvector

Соединяет два значения tsvector. Если в обоих значениях содержатся позиции лексем, позиции во втором при совмещении корректируются.

'a:1 b:2'::tsvector || 'c:1 d:2 b:3'::tsvector'a':1 'b':2,5 'c':3 'd':4

tsquery && tsquerytsquery

Вычисляет конъюнкцию двух значений tsquery, получая тем самым запрос, которому будут соответствовать документы, соответствующие обоим входным запросам.

'fat | rat'::tsquery && 'cat'::tsquery( 'fat' | 'rat' ) & 'cat'

tsquery || tsquerytsquery

Вычисляет дизъюнкцию двух значений tsquery, получая тем самым запрос, которому будут соответствовать документы, соответствующие любому из входных запросов.

'fat | rat'::tsquery || 'cat'::tsquery'fat' | 'rat' | 'cat'

!! tsquerytsquery

Вычисляет отрицание tsquery, получая тем самым запрос, которому будут соответствовать документы, не соответствующие входному запросу.

!! 'cat'::tsquery!'cat'

tsquery <-> tsquerytsquery

Конструирует фразовый запрос, которому будут соответствовать документы, содержащие подряд идущие лексемы, удовлетворяющие двум входным запросам.

to_tsquery('fat') <-> to_tsquery('rat')'fat' <-> 'rat'

tsquery @> tsqueryboolean

Первый запрос типа tsquery содержит второй? (При этом учитывается только факт нахождения всех лексем из одного запроса в другом; операторы их сочетания игнорируются.)

'cat'::tsquery @> 'cat & rat'::tsqueryf

tsquery <@ tsqueryboolean

Первый запрос типа tsquery содержится во втором? (При этом учитывается только факт нахождения всех лексем из одного запроса в другом; операторы их сочетания игнорируются.)

'cat'::tsquery <@ 'cat & rat'::tsqueryt

'cat'::tsquery <@ '!cat & rat'::tsqueryt


Помимо этих специализированных операторов, для типов tsvector и tsquery имеются обычные операторы сравнения, показанные в Таблице 9.1. Они не очень полезны для поиска, но позволяют, в частности, создавать индексы по столбцам этих типов.

Таблица 9.43. Функции текстового поиска

Функция

Описание

Пример(ы)

array_to_tsvector ( text[] ) → tsvector

Преобразует массив текстовых строк в tsvector. Переданные строки используются в виде лексем как есть, без дополнительной обработки. Элементы массива не должны быть пустыми строками или NULL.

array_to_tsvector('{fat,cat,rat}'::text[])'cat' 'fat' 'rat'

get_current_ts_config ( ) → regconfig

Возвращает OID текущей конфигурации текстового поиска по умолчанию (задаваемой параметром default_text_search_config).

get_current_ts_config()english

length ( tsvector ) → integer

Возвращает число лексем в значении tsvector.

length('fat:2,4 cat:3 rat:5A'::tsvector)3

numnode ( tsquery ) → integer

Возвращает число лексем и операторов в запросе tsquery.

numnode('(fat & rat) | cat'::tsquery)5

plainto_tsquery ( [config regconfig, ] query text ) → tsquery

Преобразует текст в tsquery, выполняя нормализацию слов согласно конфигурации по умолчанию или указанной явно. Знаки пунктуации во входной строке при этом игнорируются (в данном случае она не определяет операторы запроса). Результирующему запросу будут соответствовать документы, содержащие все слова этого текста, кроме стоп-слов.

plainto_tsquery('english', 'The Fat Rats')'fat' & 'rat'

phraseto_tsquery ( [config regconfig, ] query text ) → tsquery

Преобразует текст в tsquery, выполняя нормализацию слов согласно конфигурации по умолчанию или указанной явно. Знаки пунктуации во входной строке при этом игнорируются (в данном случае она не определяет операторы запроса). Результирующему запросу будут соответствовать фразы, содержащие последовательность слов этого текста, кроме стоп-слов.

phraseto_tsquery('english', 'The Fat Rats')'fat' <-> 'rat'

phraseto_tsquery('english', 'The Cat and Rats')'cat' <2> 'rat'

websearch_to_tsquery ( [config regconfig, ] query text ) → tsquery

Преобразует текст в tsquery, выполняя нормализацию слов согласно конфигурации по умолчанию или указанной явно. Последовательности слов в кавычках преобразуются в проверки фраз. Слово «or» воспринимается как оператор OR (ИЛИ), а символ минуса преобразуется в оператор NOT (НЕ); другие знаки пунктуации игнорируются. Это примерно соответствует поведению ряда распространённых средств поиска в вебе.

websearch_to_tsquery('english', '"fat rat" or cat dog')'fat' <-> 'rat' | 'cat' & 'dog'

querytree ( tsquery ) → text

Формирует представление индексируемой части tsquery. Если возвращается пустой результат или просто T, это означает, что запрос не индексируемый.

querytree('foo & ! bar'::tsquery)'foo'

setweight ( vector tsvector, weight "char" ) → tsvector

Назначает вес, указанный в аргументе weight, каждому элементу аргумента vector.

setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A')'cat':3A 'fat':2A,4A 'rat':5A

setweight ( vector tsvector, weight "char", lexemes text[] ) → tsvector

Назначает вес, указанный в аргументе weight, элементам аргумента vector, перечисленным в аргументе lexemes. Строки в lexemes принимаются в виде лексем как есть, без дальнейшей обработки. Строки, не соответствующие ни одной лексеме в vector, игнорируются.

setweight('fat:2,4 cat:3 rat:5,6B'::tsvector, 'A', '{cat,rat}')'cat':3A 'fat':2,4 'rat':5A,6A

strip ( tsvector ) → tsvector

Убирает позиции и веса из значения tsvector.

strip('fat:2,4 cat:3 rat:5A'::tsvector)'cat' 'fat' 'rat'

to_tsquery ( [config regconfig, ] query text ) → tsquery

Преобразует текст в tsquery, выполняя нормализацию слов согласно конфигурации по умолчанию или указанной явно. Слова должны разделяться операторами tsquery.

to_tsquery('english', 'The & Fat & Rats')'fat' & 'rat'

to_tsvector ( [config regconfig, ] document text ) → tsvector

Преобразует текст в tsvector, выполняя нормализацию слов согласно конфигурации по умолчанию или указанной явно. Результат будет включать информацию о позициях слов.

to_tsvector('english', 'The Fat Rats')'fat':2 'rat':3

to_tsvector ( [config regconfig, ] document json ) → tsvector

to_tsvector ( [config regconfig, ] document jsonb ) → tsvector

Преобразует каждое строковое значение в документе JSON в значение tsvector, выполняя нормализацию слов согласно конфигурации по умолчанию или указанной явно. В результате выдаются полученные значения, соединённые вместе в порядке следования в документе. При вычислении выдаваемых позиций слов считается, что между каждой парой строковых значений находится одно стоп-слово. (Учтите, что в случае с jsonb «порядок следования в документе» полей объекта JSON зависит от реализации; это наглядно показано в примере.)

to_tsvector('english', '{"aa": "The Fat Rats", "b": "dog"}'::json)'dog':5 'fat':2 'rat':3

to_tsvector('english', '{"aa": "The Fat Rats", "b": "dog"}'::jsonb)'dog':1 'fat':4 'rat':5

json_to_tsvector ( [config regconfig, ] document json, filter jsonb ) → tsvector

jsonb_to_tsvector ( [config regconfig, ] document jsonb, filter jsonb ) → tsvector

Выбирает из JSON-документа все элементы, соответствующие фильтру filter, и преобразует каждый в значение tsvector, нормализуя их согласно конфигурации по умолчанию или указанной явно. В результате выдаются полученные значения, соединённые вместе в порядке следования в документе. При вычислении выдаваемых позиций слов считается, что между каждой парой строковых значений находится одно стоп-слово. (Учтите, что в случае с jsonb «порядок следования в документе» полей объекта JSON зависит от реализации.) В параметре filter должен передаваться массив jsonb, содержащий ноль или более следующих ключевых слов: "string" (включить все строковые значения), "numeric" (все числовые значения), "boolean" (все логические значения), "key" (все ключи) или "all" (включить всё вышеперечисленное). В качестве особого значения filter принимается простое JSON-значение, содержащее одно из этих ключевых слов.

json_to_tsvector('english', '{"a": "The Fat Rats", "b": 123}'::json, '["string", "numeric"]')'123':5 'fat':2 'rat':3

json_to_tsvector('english', '{"cat": "The Fat Rats", "dog": 123}'::json, '"all"')'123':9 'cat':1 'dog':7 'fat':4 'rat':5

ts_delete ( vector tsvector, lexeme text ) → tsvector

Удаляет все вхождения лексемы, задаваемой аргументом lexeme, из значения vector. Строка lexeme принимается в виде лексемы как есть, без дальнейшей обработки.

ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, 'fat')'cat':3 'rat':5A

ts_delete ( vector tsvector, lexemes text[] ) → tsvector

Удаляет все вхождения лексем, переданных в параметре lexemes, из параметра vector. Строки в lexemes принимаются в виде лексем как есть, без дальнейшей обработки. Строки, которые не соответствуют никаким лексемам в vector, игнорируются.

ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, ARRAY['fat','rat'])'cat':3

ts_filter ( vector tsvector, weights "char"[] ) → tsvector

Выбирает из значения vector только элементы с весами, перечисленными в массиве weights.

ts_filter('fat:2,4 cat:3b,7c rat:5A'::tsvector, '{a,b}')'cat':3B 'rat':5A

ts_headline ( [config regconfig, ] document text, query tsquery [, options text] ) → text

Выводит в виде выдержек соответствующие поисковому запросу query фрагменты содержимого document, которое должно быть просто текстом, а не значением tsvector. Слова в документе перед поиском нормализуются согласно конфигурации по умолчанию или указанной явно. Использование этой функции рассматривается в Подразделе 12.3.4; также там описываются возможные значения options.

ts_headline('The fat cat ate the rat.', 'cat')The fat <b>cat</b> ate the rat.

ts_headline ( [config regconfig, ] document json, query tsquery [, options text] ) → text

ts_headline ( [config regconfig, ] document jsonb, query tsquery [, options text] ) → text

Выводит в виде выдержек соответствующие поисковому запросу query вхождения, найденные в строковых значениях внутри JSON-документа document. За подробностями обратитесь к Подразделу 12.3.4.

ts_headline('{"cat":"raining cats and dogs"}'::jsonb, 'cat'){"cat": "raining <b>cats</b> and dogs"}

ts_rank ( [weights real[], ] vector tsvector, query tsquery [, normalization integer] ) → real

Вычисляет оценку, показывающую, в какой степени значение vector соответствует запросу query. За подробностями обратитесь к Подразделу 12.3.3.

ts_rank(to_tsvector('raining cats and dogs'), 'cat')0.06079271

ts_rank_cd ( [weights real[], ] vector tsvector, query tsquery [, normalization integer] ) → real

Вычисляет по алгоритму расчёта плотности покрытия оценку, показывающую, в какой степени значение vector соответствует запросу query За подробностями обратитесь к Подразделу 12.3.3.

ts_rank_cd(to_tsvector('raining cats and dogs'), 'cat')0.1

ts_rewrite ( query tsquery, target tsquery, substitute tsquery ) → tsquery

Заменяет в аргументе query вхождения target значением substitute. За подробностями обратитесь к Подразделу 12.4.2.1.

ts_rewrite('a & b'::tsquery, 'a'::tsquery, 'foo|bar'::tsquery)'b' & ( 'foo' | 'bar' )

ts_rewrite ( query tsquery, select text ) → tsquery

Заменяет фрагменты запроса query, извлекая искомое вхождение и замену для него с помощью команды SELECT. За подробностями обратитесь к Подразделу 12.4.2.1.

SELECT ts_rewrite('a & b'::tsquery, 'SELECT t,s FROM aliases')'b' & ( 'foo' | 'bar' )

tsquery_phrase ( query1 tsquery, query2 tsquery ) → tsquery

Конструирует фразовый запрос, который будет находить подряд идущие лексемы, удовлетворяющие запросам query1 и query2 (как делает оператор <->).

tsquery_phrase(to_tsquery('fat'), to_tsquery('cat'))'fat' <-> 'cat'

tsquery_phrase ( query1 tsquery, query2 tsquery, distance integer ) → tsquery

Конструирует фразовый запрос, который будет находить вхождения, удовлетворяющие запросам query1 и query2, на расстоянии ровно в distance лексем друг от друга.

tsquery_phrase(to_tsquery('fat'), to_tsquery('cat'), 10)'fat' <10> 'cat'

tsvector_to_array ( tsvector ) → text[]

Преобразует tsvector в массив лексем.

tsvector_to_array('fat:2,4 cat:3 rat:5A'::tsvector){cat,fat,rat}

unnest ( tsvector ) → setof record ( lexeme text, positions smallint[], weights text )

Разворачивает tsvector в набор строк, по одной лексеме в строке.

select * from unnest('cat:3 fat:2,4 rat:5A'::tsvector)

 lexeme | positions | weights
--------+-----------+---------
 cat    | {3}       | {D}
 fat    | {2,4}     | {D,D}
 rat    | {5}       | {A}


Примечание

Все функции текстового поиска, принимающие необязательный аргумент regconfig, будут использовать конфигурацию, указанную в параметре default_text_search_config, когда этот аргумент опущен.

Функции в Таблице 9.44 перечислены отдельно, так как они не очень полезны в традиционных операциях поиска. Они предназначены в основном для разработки и отладки новых конфигураций текстового поиска.

Таблица 9.44. Функции отладки текстового поиска

Функция

Описание

Пример(ы)

ts_debug ( [config regconfig, ] document text ) → setof record ( alias text, description text, token text, dictionaries regdictionary[], dictionary regdictionary, lexemes text[] )

Извлекает из текста document фрагменты, нормализуя их согласно конфигурации текстового поиска по умолчанию или указанной явно, и выдаёт информацию о том, как был обработан каждый фрагмент. За подробностями обратитесь к Подразделу 12.8.1.

ts_debug('english', 'The Brightest supernovaes')(asciiword,"Word, all ASCII",The,{​english_stem​},​english_stem,{}) ...

ts_lexize ( dict regdictionary, token text ) → text[]

Возвращает массив заменяющих лексем, если слово, заданное аргументом token, есть в словаре, пустой массив, если это стоп-слово, которое есть в словаре, либо NULL, если такого слова нет. За подробностями обратитесь к Подразделу 12.8.3.

ts_lexize('english_stem', 'stars'){star}

ts_parse ( parser_name text, document text ) → setof record ( tokid integer, token text )

Извлекает фрагменты из текста document, применяя анализатор с указанным именем. За подробностями обратитесь к Подразделу 12.8.2.

ts_parse('default', 'foo - bar')(1,foo) ...

ts_parse ( parser_oid oid, document text ) → setof record ( tokid integer, token text )

Извлекает фрагменты из текста document, применяя анализатор с указанным OID. За подробностями обратитесь к Подразделу 12.8.2.

ts_parse(3722, 'foo - bar')(1,foo) ...

ts_token_type ( parser_name text ) → setof record ( tokid integer, alias text, description text )

Возвращает таблицу, описывающую все типы фрагментов, которые может распознать анализатор с указанным именем. За подробностями обратитесь к Подразделу 12.8.2.

ts_token_type('default')(1,asciiword,"Word, all ASCII") ...

ts_token_type ( parser_oid oid ) → setof record ( tokid integer, alias text, description text )

Возвращает таблицу, описывающую все типы фрагментов, которые может распознать анализатор с указанным OID. За подробностями обратитесь к Подразделу 12.8.2.

ts_token_type(3722)(1,asciiword,"Word, all ASCII") ...

ts_stat ( sqlquery text [, weights text] ) → setof record ( word text, ndoc integer, nentry integer )

Выполняет запрос sqlquery, который должен возвращать единственный столбец tsvector, и выдаёт статистику по каждой отдельной лексеме, содержащейся в данных. За подробностями обратитесь к Подразделу 12.4.4.

ts_stat('SELECT vector FROM apod')(foo,10,15) ...


9.13. Text Search Functions and Operators

Table 9.42, Table 9.43 and Table 9.44 summarize the functions and operators that are provided for full text searching. See Chapter 12 for a detailed explanation of Postgres Pro's text search facility.

Table 9.42. Text Search Operators

Operator

Description

Example(s)

tsvector @@ tsqueryboolean

tsquery @@ tsvectorboolean

Does tsvector match tsquery? (The arguments can be given in either order.)

to_tsvector('fat cats ate rats') @@ to_tsquery('cat & rat')t

text @@ tsqueryboolean

Does text string, after implicit invocation of to_tsvector(), match tsquery?

'fat cats ate rats' @@ to_tsquery('cat & rat')t

tsvector @@@ tsqueryboolean

tsquery @@@ tsvectorboolean

This is a deprecated synonym for @@.

to_tsvector('fat cats ate rats') @@@ to_tsquery('cat & rat')t

tsvector || tsvectortsvector

Concatenates two tsvectors. If both inputs contain lexeme positions, the second input's positions are adjusted accordingly.

'a:1 b:2'::tsvector || 'c:1 d:2 b:3'::tsvector'a':1 'b':2,5 'c':3 'd':4

tsquery && tsquerytsquery

ANDs two tsquerys together, producing a query that matches documents that match both input queries.

'fat | rat'::tsquery && 'cat'::tsquery( 'fat' | 'rat' ) & 'cat'

tsquery || tsquerytsquery

ORs two tsquerys together, producing a query that matches documents that match either input query.

'fat | rat'::tsquery || 'cat'::tsquery'fat' | 'rat' | 'cat'

!! tsquerytsquery

Negates a tsquery, producing a query that matches documents that do not match the input query.

!! 'cat'::tsquery!'cat'

tsquery <-> tsquerytsquery

Constructs a phrase query, which matches if the two input queries match at successive lexemes.

to_tsquery('fat') <-> to_tsquery('rat')'fat' <-> 'rat'

tsquery @> tsqueryboolean

Does first tsquery contain the second? (This considers only whether all the lexemes appearing in one query appear in the other, ignoring the combining operators.)

'cat'::tsquery @> 'cat & rat'::tsqueryf

tsquery <@ tsqueryboolean

Is first tsquery contained in the second? (This considers only whether all the lexemes appearing in one query appear in the other, ignoring the combining operators.)

'cat'::tsquery <@ 'cat & rat'::tsqueryt

'cat'::tsquery <@ '!cat & rat'::tsqueryt


In addition to these specialized operators, the usual comparison operators shown in Table 9.1 are available for types tsvector and tsquery. These are not very useful for text searching but allow, for example, unique indexes to be built on columns of these types.

Table 9.43. Text Search Functions

Function

Description

Example(s)

array_to_tsvector ( text[] ) → tsvector

Converts an array of text strings to a tsvector. The given strings are used as lexemes as-is, without further processing. Array elements must not be empty strings or NULL.

array_to_tsvector('{fat,cat,rat}'::text[])'cat' 'fat' 'rat'

get_current_ts_config ( ) → regconfig

Returns the OID of the current default text search configuration (as set by default_text_search_config).

get_current_ts_config()english

length ( tsvector ) → integer

Returns the number of lexemes in the tsvector.

length('fat:2,4 cat:3 rat:5A'::tsvector)3

numnode ( tsquery ) → integer

Returns the number of lexemes plus operators in the tsquery.

numnode('(fat & rat) | cat'::tsquery)5

plainto_tsquery ( [ config regconfig, ] query text ) → tsquery

Converts text to a tsquery, normalizing words according to the specified or default configuration. Any punctuation in the string is ignored (it does not determine query operators). The resulting query matches documents containing all non-stopwords in the text.

plainto_tsquery('english', 'The Fat Rats')'fat' & 'rat'

phraseto_tsquery ( [ config regconfig, ] query text ) → tsquery

Converts text to a tsquery, normalizing words according to the specified or default configuration. Any punctuation in the string is ignored (it does not determine query operators). The resulting query matches phrases containing all non-stopwords in the text.

phraseto_tsquery('english', 'The Fat Rats')'fat' <-> 'rat'

phraseto_tsquery('english', 'The Cat and Rats')'cat' <2> 'rat'

websearch_to_tsquery ( [ config regconfig, ] query text ) → tsquery

Converts text to a tsquery, normalizing words according to the specified or default configuration. Quoted word sequences are converted to phrase tests. The word or is understood as producing an OR operator, and a dash produces a NOT operator; other punctuation is ignored. This approximates the behavior of some common web search tools.

websearch_to_tsquery('english', '"fat rat" or cat dog')'fat' <-> 'rat' | 'cat' & 'dog'

querytree ( tsquery ) → text

Produces a representation of the indexable portion of a tsquery. A result that is empty or just T indicates a non-indexable query.

querytree('foo & ! bar'::tsquery)'foo'

setweight ( vector tsvector, weight "char" ) → tsvector

Assigns the specified weight to each element of the vector.

setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A')'cat':3A 'fat':2A,4A 'rat':5A

setweight ( vector tsvector, weight "char", lexemes text[] ) → tsvector

Assigns the specified weight to elements of the vector that are listed in lexemes. The strings in lexemes are taken as lexemes as-is, without further processing. Strings that do not match any lexeme in vector are ignored.

setweight('fat:2,4 cat:3 rat:5,6B'::tsvector, 'A', '{cat,rat}')'cat':3A 'fat':2,4 'rat':5A,6A

strip ( tsvector ) → tsvector

Removes positions and weights from the tsvector.

strip('fat:2,4 cat:3 rat:5A'::tsvector)'cat' 'fat' 'rat'

to_tsquery ( [ config regconfig, ] query text ) → tsquery

Converts text to a tsquery, normalizing words according to the specified or default configuration. The words must be combined by valid tsquery operators.

to_tsquery('english', 'The & Fat & Rats')'fat' & 'rat'

to_tsvector ( [ config regconfig, ] document text ) → tsvector

Converts text to a tsvector, normalizing words according to the specified or default configuration. Position information is included in the result.

to_tsvector('english', 'The Fat Rats')'fat':2 'rat':3

to_tsvector ( [ config regconfig, ] document json ) → tsvector

to_tsvector ( [ config regconfig, ] document jsonb ) → tsvector

Converts each string value in the JSON document to a tsvector, normalizing words according to the specified or default configuration. The results are then concatenated in document order to produce the output. Position information is generated as though one stopword exists between each pair of string values. (Beware that document order of the fields of a JSON object is implementation-dependent when the input is jsonb; observe the difference in the examples.)

to_tsvector('english', '{"aa": "The Fat Rats", "b": "dog"}'::json)'dog':5 'fat':2 'rat':3

to_tsvector('english', '{"aa": "The Fat Rats", "b": "dog"}'::jsonb)'dog':1 'fat':4 'rat':5

json_to_tsvector ( [ config regconfig, ] document json, filter jsonb ) → tsvector

jsonb_to_tsvector ( [ config regconfig, ] document jsonb, filter jsonb ) → tsvector

Selects each item in the JSON document that is requested by the filter and converts each one to a tsvector, normalizing words according to the specified or default configuration. The results are then concatenated in document order to produce the output. Position information is generated as though one stopword exists between each pair of selected items. (Beware that document order of the fields of a JSON object is implementation-dependent when the input is jsonb.) The filter must be a jsonb array containing zero or more of these keywords: "string" (to include all string values), "numeric" (to include all numeric values), "boolean" (to include all boolean values), "key" (to include all keys), or "all" (to include all the above). As a special case, the filter can also be a simple JSON value that is one of these keywords.

json_to_tsvector('english', '{"a": "The Fat Rats", "b": 123}'::json, '["string", "numeric"]')'123':5 'fat':2 'rat':3

json_to_tsvector('english', '{"cat": "The Fat Rats", "dog": 123}'::json, '"all"')'123':9 'cat':1 'dog':7 'fat':4 'rat':5

ts_delete ( vector tsvector, lexeme text ) → tsvector

Removes any occurrence of the given lexeme from the vector. The lexeme string is treated as a lexeme as-is, without further processing.

ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, 'fat')'cat':3 'rat':5A

ts_delete ( vector tsvector, lexemes text[] ) → tsvector

Removes any occurrences of the lexemes in lexemes from the vector. The strings in lexemes are taken as lexemes as-is, without further processing. Strings that do not match any lexeme in vector are ignored.

ts_delete('fat:2,4 cat:3 rat:5A'::tsvector, ARRAY['fat','rat'])'cat':3

ts_filter ( vector tsvector, weights "char"[] ) → tsvector

Selects only elements with the given weights from the vector.

ts_filter('fat:2,4 cat:3b,7c rat:5A'::tsvector, '{a,b}')'cat':3B 'rat':5A

ts_headline ( [ config regconfig, ] document text, query tsquery [, options text ] ) → text

Displays, in an abbreviated form, the match(es) for the query in the document, which must be raw text not a tsvector. Words in the document are normalized according to the specified or default configuration before matching to the query. Use of this function is