WarehousePG supports built-in functions and operators including analytic functions and window functions that can be used in window expressions. For information about using built-in WarehousePG functions see, "Using Functions and Operators" in the WarehousePG Administrator Guide.
- WarehousePG Function Types
- Built-in Functions and Operators
- JSON Functions and Operators
- Window Functions
- Advanced Aggregate Functions
- Text Search Functions and Operators
- Range Functions and Operators
Parent topic: WarehousePG Reference Guide
WarehousePG Function Types
WarehousePG evaluates functions and operators used in SQL expressions. Some functions and operators are only allowed to run on the coordinator since they could lead to inconsistencies in WarehousePG segment instances. The following describes the WarehousePG function types.
IMMUTABLE
WarehousePG support: Yes
Relies only on information directly in its argument list. Given the same argument values, always returns the same result.
STABLE
WarehousePG support: Yes, in most cases
Within a single table scan, returns the same result for same argument values, but results change across SQL statements.
Results depend on database lookups or parameter values. The current_timestamp family of functions is STABLE, and values don't change within an execution.
VOLATILE
WarehousePG support: Restricted
Function values can change within a single table scan. For example, random() and timeofday().
Any function with side effects is volatile, even if its result is predictable. For example, setval().
In WarehousePG, data is divided up across segments — each segment is a distinct PostgreSQL database. To prevent inconsistent or unexpected results, do not run functions classified as VOLATILE at the segment level if they contain SQL commands or modify the database in any way. For example, functions such as setval() are not allowed to run on distributed data in WarehousePG because they can cause inconsistent data between segment instances.
To ensure data consistency, you can safely use VOLATILE and STABLE functions in statements that are evaluated on and run from the coordinator. For example, the following statements run on the coordinator (statements without a FROM clause):
SELECT setval('myseq', 201);
SELECT foo();If a statement has a FROM clause containing a distributed table and the function in the FROM clause returns a set of rows, the statement can run on the segments:
SELECT * from foo();
WarehousePG does not support functions that return a table reference (rangeFuncs) or functions that use the refCursor datatype.
Built-in Functions and Operators
The following table lists the categories of built-in functions and operators supported by PostgreSQL. All functions and operators are supported in WarehousePG as in PostgreSQL with the exception of STABLE and VOLATILE functions, which are subject to the restrictions noted in WarehousePG Function Types. See the Functions and Operators section of the PostgreSQL documentation for more information about these built-in functions and operators.
| Operator/Function Category | VOLATILE Functions | STABLE Functions | Restrictions | |||||
|---|---|---|---|---|---|---|---|---|
| Logical Operators | ||||||||
| Comparison Operators | ||||||||
| Mathematical Functions and Operators | random setseed | |||||||
| String Functions and Operators | All built-in conversion functions | convert pg_client_encoding | ||||||
| Binary String Functions and Operators | ||||||||
| Bit String Functions and Operators | ||||||||
| Pattern Matching | ||||||||
| Data Type Formatting Functions | to_char to_timestamp | |||||||
| Date/Time Functions and Operators | timeofday | age current_date current_time current_timestamp localtime localtimestamp now | ||||||
| Enum Support Functions | ||||||||
| Geometric Functions and Operators | ||||||||
| Network Address Functions and Operators | ||||||||
| Sequence Manipulation Functions | nextval() setval() | |||||||
| Conditional Expressions | ||||||||
| Array Functions and Operators | All array functions | |||||||
| Aggregate Functions | ||||||||
| Subquery Expressions | ||||||||
| Row and Array Comparisons | ||||||||
| Set Returning Functions | generate_series | |||||||
| System Information Functions | All session information functions All access privilege inquiry functions All schema visibility inquiry functions All system catalog information functions All comment information functions All transaction ids and snapshots | |||||||
| System Administration Functions | set_config pg_cancel_backend pg_reload_conf pg_rotate_logfile pg_start_backup pg_stop_backup pg_size_pretty pg_ls_dir pg_read_file pg_stat_file | current_setting All database object size functions | > Note The function pg_column_size displays bytes required to store the value, possibly with TOAST compression. | |||||
| XML Functions and function-like expressions | cursor_to_xml(cursor refcursor, count int, nulls boolean, tableforest boolean, targetns text) cursor_to_xmlschema(cursor refcursor, nulls boolean, tableforest boolean, targetns text) database_to_xml(nulls boolean, tableforest boolean, targetns text) database_to_xmlschema(nulls boolean, tableforest boolean, targetns text) database_to_xml_and_xmlschema(nulls boolean, tableforest boolean, targetns text) query_to_xml(query text, nulls boolean, tableforest boolean, targetns text) query_to_xmlschema(query text, nulls boolean, tableforest boolean, targetns text) query_to_xml_and_xmlschema(query text, nulls boolean, tableforest boolean, targetns text) schema_to_xml(schema name, nulls boolean, tableforest boolean, targetns text) schema_to_xmlschema(schema name, nulls boolean, tableforest boolean, targetns text) schema_to_xml_and_xmlschema(schema name, nulls boolean, tableforest boolean, targetns text) table_to_xml(tbl regclass, nulls boolean, tableforest boolean, targetns text) table_to_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text) table_to_xml_and_xmlschema(tbl regclass, nulls boolean, tableforest boolean, targetns text) xmlagg(xml) xmlconcat(xml[, ...]) xmlelement(name name [, xmlattributes(value [AS attname] [, ... ])] [, content, ...]) xmlexists(text, xml) xmlforest(content [AS name] [, ...]) xml_is_well_formed(text) xml_is_well_formed_document(text) xml_is_well_formed_content(text) xmlparse ( { DOCUMENT | CONTENT } value) xpath(text, xml) xpath(text, xml, text[]) xpath_exists(text, xml) xpath_exists(text, xml, text[]) xmlpi(name target [, content]) xmlroot(xml, version text | no value [, standalone yes | no | no value]) xmlserialize ( { DOCUMENT | CONTENT } value AS type ) xml(text) text(xml) xmlcomment(xml) xmlconcat2(xml, xml) |
JSON Functions and Operators
WarehousePG includes built-in functions and operators that create and manipulate JSON data.
Note For
jsondata type values, all key/value pairs are kept even if a JSON object contains duplicate keys. For duplicate keys, JSON processing functions consider the last value as the operative one. For thejsonbdata type, duplicate object keys are not kept. If the input includes duplicate keys, only the last value is kept. See About JSON Datain the WarehousePG Administrator Guide.
JSON Operators
The following operators are available for use with the json and jsonb data types.
-> (int)
Right operand type: int
Get the JSON array element (indexed from zero).
Example:
'[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json->2
{"c":"baz"}-> (text)
Right operand type: text
Get the JSON object field by key.
Example:
'{"a": {"b":"foo"}}'::json->'a'
{"b":"foo"}->> (int)
Right operand type: int
Get the JSON array element as text.
Example:
'[1,2,3]'::json->>2 3
->> (text)
Right operand type: text
Get the JSON object field as text.
Example:
'{"a":1,"b":2}'::json->>'b'
2#>
Right operand type: text[]
Get the JSON object at specified path.
Example:
'{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}'
{"c": "foo"}#>>
Right operand type: text[]
Get the JSON object at specified path as text.
Example:
'{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}'
3Note There are parallel variants of these operators for both the
jsonandjsonbdata types. The field, element, and path extraction operators return the same data type as their left-hand input (eitherjsonorjsonb), except for those specified as returningtext, which coerce the value totext. The field, element, and path extraction operators returnNULL, rather than failing, if the JSON input does not have the right structure to match the request; for example if no such element exists.
Operators that require the jsonb data type as the left operand are described next. Many of these operators can be indexed by jsonb operator classes. For a full description of jsonb containment and existence semantics, see jsonb Containment and Existencein the WarehousePG Administrator Guide. For information about how these operators can be used to effectively index jsonb data, see jsonb Indexingin the WarehousePG Administrator Guide.
@>
Right operand type: jsonb
Does the left JSON value contain within it the right value?
Example:
'{"a":1, "b":2}'::jsonb @> '{"b":2}'::jsonb<@
Right operand type: jsonb
Is the left JSON value contained within the right value?
Example:
'{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonb?
Right operand type: text
Does the key/element string exist within the JSON value?
Example:
'{"a":1, "b":2}'::jsonb ? 'b'?|
Right operand type: text[]
Do any of these key/element strings exist?
Example:
'{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c']?&
Right operand type: text[]
Do all of these key/element strings exist?
Example:
'["a", "b"]'::jsonb ?& array['a', 'b']
The following standard comparison operators are available only for the jsonb data type, not for the json data type. They follow the ordering rules for B-tree operations described in jsonb Indexingin the WarehousePG Administrator Guide.
<(less than)>(greater than)<=(less than or equal to)>=(greater than or equal to)=(equal)<>or!=(not equal)
Note The
!=operator is converted to<>in the parser stage. It is not possible to implement!=and<>operators that do different things.
JSON Creation Functions
The following functions create json data type values. (Currently, there are no equivalent functions for jsonb, but you can cast the result of one of these functions to jsonb.)
to_json(anyelement)
Returns the value as a JSON object. Arrays and composites are processed recursively and are converted to arrays and objects. If the input contains a cast from the type to json, the cast function is used to perform the conversion. Otherwise, a JSON scalar value is produced. For any scalar type other than a number, a Boolean, or a null value, the text representation is used, properly quoted and escaped so that it is a valid JSON string.
Example:
to_json('Fred said "Hi."'::text)
"Fred said \"Hi.\""array_to_json(anyarray [, pretty_bool])
Returns the array as a JSON array. A multidimensional array becomes a JSON array of arrays. Line feeds are added between dimension-1 elements if pretty_bool is true.
Example:
array_to_json('{ {1,5},{99,100}}'::int[])
[[1,5],[99,100]]row_to_json(record [, pretty_bool])
Returns the row as a JSON object. Line feeds are added between level-1 elements if pretty_bool is true.
Example:
row_to_json(row(1,'foo'))
{"f1":1,"f2":"foo"}json_build_array(VARIADIC "any")
Builds a possibly heterogeneously typed JSON array out of a VARIADIC argument list.
Example:
json_build_array(1,2,'3',4,5) [1, 2, "3", 4, 5]
json_build_object(VARIADIC "any")
Builds a JSON object out of a VARIADIC argument list. The argument list is taken in order and converted to a set of key/value pairs.
Example:
json_build_object('foo',1,'bar',2)
{"foo": 1, "bar": 2}json_object(text[])
Builds a JSON object out of a text array. The array must be either a one or a two dimensional array.
The one dimensional array must have an even number of elements. The elements are taken as key/value pairs.
For a two dimensional array, each inner array must have exactly two elements, which are taken as a key/value pair.
Example:
json_object('{a, 1, b, "def", c, 3.5}')
json_object('{ {a, 1},{b, "def"},{c, 3.5}}')
{"a": "1", "b": "def", "c": "3.5"}json_object(keys text[], values text[])
Builds a JSON object out of a text array. This form of json_object takes keys and values pairwise from two separate arrays. In all other respects it is identical to the one-argument form.
Example:
json_object('{a, b}', '{1,2}')
{"a": "1", "b": "2"}Note
array_to_jsonandrow_to_jsonhave the same behavior asto_jsonexcept for offering a pretty-printing option. The behavior described forto_jsonlikewise applies to each individual value converted by the other JSON creation functions.
Note The hstore extension has a cast from
hstoretojson, so thathstorevalues converted via the JSON creation functions will be represented as JSON objects, not as primitive string values.
JSON Aggregate Functions
The following functions aggregate records to an array of JSON objects and pairs of values to a JSON object.
json_agg(record)
Argument types: record
Return type: json
Aggregates records as a JSON array of objects.
json_object_agg(name, value)
Argument types: ("any", "any")
Return type: json
Aggregates name/value pairs as a JSON object.
JSON Processing Functions
This section describes the functions that are available for processing json and jsonb values.
Many of these processing functions and operators convert Unicode escapes in JSON strings to the appropriate single character. This is a not an issue if the input data type is jsonb, because the conversion was already done. However, for json data type input, this might result in an error being thrown. See About JSON Data.
json_array_length() / jsonb_array_length()
Syntax: json_array_length(json) / jsonb_array_length(jsonb)
Return type: int
Returns the number of elements in the outermost JSON array.
Example:
json_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]')
5json_each() / jsonb_each()
Syntax: json_each(json) / jsonb_each(jsonb)
Return type: setof key text, value json / setof key text, value jsonb
Expands the outermost JSON object into a set of key/value pairs.
Example:
select * from json_each('{"a":"foo", "b":"bar"}')
key | value
-----+-------
a | "foo"
b | "bar"json_each_text() / jsonb_each_text()
Syntax: json_each_text(json) / jsonb_each_text(jsonb)
Return type: setof key text, value text
Expands the outermost JSON object into a set of key/value pairs. The returned values will be of type text.
Example:
select * from json_each_text('{"a":"foo", "b":"bar"}')
key | value
-----+-------
a | foo
b | barjson_extract_path() / jsonb_extract_path()
Syntax: json_extract_path(from_json json, VARIADIC path_elems text[]) / jsonb_extract_path(from_json jsonb, VARIADIC path_elems text[])
Return type: json / jsonb
Returns the JSON value pointed to by path_elems (equivalent to #> operator).
Example:
json_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4')
{"f5":99,"f6":"foo"}json_extract_path_text() / jsonb_extract_path_text()
Syntax: json_extract_path_text(from_json json, VARIADIC path_elems text[]) / jsonb_extract_path_text(from_json jsonb, VARIADIC path_elems text[])
Return type: text
Returns the JSON value pointed to by path_elems as text. Equivalent to #>> operator.
Example:
json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4', 'f6')
foojson_object_keys() / jsonb_object_keys()
Syntax: json_object_keys(json) / jsonb_object_keys(jsonb)
Return type: setof text
Returns set of keys in the outermost JSON object.
Example:
json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')
json_object_keys
------------------
f1
f2json_populate_record() / jsonb_populate_record()
Syntax: json_populate_record(base anyelement, from_json json) / jsonb_populate_record(base anyelement, from_json jsonb)
Return type: anyelement
Expands the object in from_json to a row whose columns match the record type defined by base. See Note 1.
Example:
select * from json_populate_record(null::myrowtype, '{"a":1,"b":2}')
a | b
---+---
1 | 2json_populate_recordset() / jsonb_populate_recordset()
Syntax: json_populate_recordset(base anyelement, from_json json) / jsonb_populate_recordset(base anyelement, from_json jsonb)
Return type: setof anyelement
Expands the outermost array of objects in from_json to a set of rows whose columns match the record type defined by base. See Note 1.
Example:
select * from json_populate_recordset(null::myrowtype, '[{"a":1,"b":2},{"a":3,"b":4}]')
a | b
---+---
1 | 2
3 | 4json_array_elements() / jsonb_array_elements()
Syntax: json_array_elements(json) / jsonb_array_elements(jsonb)
Return type: setof json / setof jsonb
Expands a JSON array to a set of JSON values.
Example:
select * from json_array_elements('[1,true, [2,false]]')
value
-----------
1
true
[2,false]json_array_elements_text() / jsonb_array_elements_text()
Syntax: json_array_elements_text(json) / jsonb_array_elements_text(jsonb)
Return type: setof text
Expands a JSON array to a set of text values.
Example:
select * from json_array_elements_text('["foo", "bar"]')
value
-----------
foo
barjson_typeof() / jsonb_typeof()
Syntax: json_typeof(json) / jsonb_typeof(jsonb)
Return type: text
Returns the type of the outermost JSON value as a text string. Possible types are object, array, string, number, boolean, and null. See Note.
Example:
json_typeof('-123.4')
numberjson_to_record() / jsonb_to_record()
Syntax: json_to_record(json) / jsonb_to_record(jsonb)
Return type: record
Builds an arbitrary record from a JSON object. See Note 1.
As with all functions returning record, the caller must explicitly define the structure of the record with an AS clause.
Example:
select * from json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}') as x(a int, b text, d text)
a | b | d
---+---------+---
1 | [1,2,3] |json_to_recordset() / jsonb_to_recordset()
Syntax: json_to_recordset(json) / jsonb_to_recordset(jsonb)
Return type: setof record
Builds an arbitrary set of records from a JSON array of objects See Note 1.
As with all functions returning record, the caller must explicitly define the structure of the record with an AS clause.
Example:
select * from json_to_recordset('[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]') as x(a int, b text);
a | b
---+-----
1 | foo
2 |Note on JSON processing functions examples
Note The examples for the functions
json_populate_record(),json_populate_recordset(),json_to_record()andjson_to_recordset()use constants. However, the typical use would be to reference a table in theFROMclause and use one of itsjsonorjsonbcolumns as an argument to the function. The extracted key values can then be referenced in other parts of the query. For example the value can be referenced inWHEREclauses and target lists. Extracting multiple values in this way can improve performance over extracting them separately with per-key operators.
JSON keys are matched to identical column names in the target row type. JSON type coercion for these functions might not result in desired values for some types. JSON fields that do not appear in the target row type will be omitted from the output, and target columns that do not match any JSON field will be
NULL.
The
json_typeoffunction null return value ofnullshould not be confused with a SQLNULL. While callingjson_typeof('null'::json)will returnnull, callingjson_typeof(NULL::json)will return a SQLNULL.
Window Functions
The following are WarehousePG built-in window functions. All window functions are immutable. For more information about window functions, see "Window Expressions" in the WarehousePG Administrator Guide.
cume_dist()
Return type: double precision
Full syntax: CUME_DIST() OVER ( [PARTITION BY expr ] ORDER BY expr )
Calculates the cumulative distribution of a value in a group of values. Rows with equal values always evaluate to the same cumulative distribution value.
dense_rank()
Return type: bigint
Full syntax: DENSE_RANK () OVER ( [PARTITION BY expr ] ORDER BY expr )
Computes the rank of a row in an ordered group of rows without skipping rank values. Rows with equal values are given the same rank value.
first_value(expr)
Return type: same as input expr type
Full syntax: FIRST_VALUE( expr ) OVER ( [PARTITION BY expr ] ORDER BY expr [ROWS | RANGE frame_expr ] )
Returns the first value in an ordered set of values.
lag(expr [,offset] [,default])
Return type: same as input expr type
Full syntax: LAG( expr [, offset ] [, default ]) OVER ( [PARTITION BY expr ] ORDER BY expr )
Provides access to more than one row of the same table without doing a self join. Given a series of rows returned from a query and a position of the cursor, LAG provides access to a row at a given physical offset prior to that position. The default offset is 1. default sets the value that is returned if the offset goes beyond the scope of the window. If default is not specified, the default value is null.
last_value(expr)
Return type: same as input expr type
Full syntax: LAST_VALUE( expr ) OVER ( [PARTITION BY expr ] ORDER BY expr [ROWS | RANGE frame_expr ] )
Returns the last value in an ordered set of values.
lead(expr [,offset] [,default])
Return type: same as input expr type
Full syntax: LEAD( expr [, offset ] [, default ]) OVER ( [PARTITION BY expr ] ORDER BY expr )
Provides access to more than one row of the same table without doing a self join. Given a series of rows returned from a query and a position of the cursor, lead provides access to a row at a given physical offset after that position. If offset is not specified, the default offset is 1. default sets the value that is returned if the offset goes beyond the scope of the window. If default is not specified, the default value is null.
ntile(expr)
Return type: bigint
Full syntax: NTILE(expr) OVER ( [PARTITION BY expr] ORDER BY expr )
Divides an ordered data set into a number of buckets (as defined by expr) and assigns a bucket number to each row.
percent_rank()
Return type: double precision
Full syntax: PERCENT_RANK () OVER ( [PARTITION BY expr] ORDER BY expr)
Calculates the rank of a hypothetical row R minus 1, divided by 1 less than the number of rows being evaluated (within a window partition).
rank()
Return type: bigint
Full syntax: RANK () OVER ( [PARTITION BY expr] ORDER BY expr)
Calculates the rank of a row in an ordered group of values. Rows with equal values for the ranking criteria receive the same rank. The number of tied rows are added to the rank number to calculate the next rank value. Ranks may not be consecutive numbers in this case.
row_number()
Return type: bigint
Full syntax: ROW_NUMBER () OVER ( [PARTITION BY expr] ORDER BY expr)
Assigns a unique number to each row to which it is applied (either each row in a window partition or each row of the query).
Advanced Aggregate Functions
The following built-in advanced analytic functions are WarehousePG extensions of the PostgreSQL database. Analytic functions are immutable.
Note The WarehousePG MADlib Extension for Analytics provides additional advanced functions to perform statistical analysis and machine learning with WarehousePG data. See MADlib Extension for Analytics.
pivot_sum (label[], label, expr)
Return type: int[], bigint[], float[]
Full syntax: pivot_sum( array['A1','A2'], attr, value)
A pivot aggregation using sum to resolve duplicate entries.
unnest (array[])
Return type: set of anyelement
Full syntax: unnest( array['one', 'row', 'per', 'item'])
Transforms a one dimensional array into rows. Returns a set of anyelement, a polymorphic pseudotype in PostgreSQL.
MEDIAN (expr)
Return type: timestamp, timestamptz, interval, float
Full syntax: MEDIAN (expression)
Can take a two-dimensional array as input. Treats such arrays as matrices.
Example:
SELECT department_id, MEDIAN(salary) FROM employees GROUP BY department_id;
PERCENTILE_CONT (expr) WITHIN GROUP (ORDER BY expr [DESC/ASC])
Return type: timestamp, timestamptz, interval, float
Full syntax: PERCENTILE_CONT(percentage) WITHIN GROUP (ORDER BY expression)
Performs an inverse distribution function that assumes a continuous distribution model. It takes a percentile value and a sort specification and returns the same datatype as the numeric datatype of the argument. This returned value is a computed result after performing linear interpolation. Null are ignored in this calculation.
Example:
SELECT department_id, PERCENTILE_CONT (0.5) WITHIN GROUP (ORDER BY salary DESC) "Median_cont"; FROM employees GROUP BY department_id;
PERCENTILE_DISC (expr) WITHIN GROUP (ORDER BY expr [DESC/ASC])
Return type: timestamp, timestamptz, interval, float
Full syntax: PERCENTILE_DISC(percentage) WITHIN GROUP (ORDER BY expression)
Performs an inverse distribution function that assumes a discrete distribution model. It takes a percentile value and a sort specification. This returned value is an element from the set. Null are ignored in this calculation.
Example:
SELECT department_id, PERCENTILE_DISC (0.5) WITHIN GROUP (ORDER BY salary DESC) "Median_desc"; FROM employees GROUP BY department_id;
sum(array[])
Return type: smallint[]int[], bigint[], float[]
Full syntax: sum(array[[1,2],[3,4]])
Performs matrix summation. Can take as input a two-dimensional array that is treated as a matrix.
Example:
CREATE TABLE mymatrix (myvalue int[]);
INSERT INTO mymatrix VALUES (array[[1,2],[3,4]]);
INSERT INTO mymatrix VALUES (array[[0,1],[1,0]]);
SELECT sum(myvalue) FROM mymatrix;
sum
---------------
{{1,3},{4,4}}Text Search Functions and Operators
The following sections summarize the functions and operators that are provided for full text searching. See Using Full Text Search for a detailed explanation of WarehousePG's text search facility.
@@
tsvector matches tsquery?
Example:
to_tsvector('fat cats ate rats') @@ to_tsquery('cat & rat')
t@@@
Deprecated synonym for @@.
Example:
to_tsvector('fat cats ate rats') @@@ to_tsquery('cat & rat')
t|| (tsvector)
Concatenates tsvectors.
Example:
'a:1 b:2'::tsvector || 'c:1 d:2 b:3'::tsvector 'a':1 'b':2,5 'c':3 'd':4
&&
ANDs tsquerys together.
Example:
'fat | rat'::tsquery && 'cat'::tsquery ( 'fat' | 'rat' ) & 'cat'
|| (tsquery)
ORs tsquerys together.
Example:
'fat | rat'::tsquery || 'cat'::tsquery ( 'fat' | 'rat' ) | 'cat'
!!
Negates a tsquery.
Example:
!! 'cat'::tsquery !'cat'
@> (tsquery)
Does one tsquery contain another?
Example:
'cat'::tsquery @> 'cat & rat'::tsquery f
<@ (tsquery)
Is one tsquery contained in another?
Example:
'cat'::tsquery <@ 'cat & rat'::tsquery t
Note The
tsquerycontainment operators consider only the lexemes listed in the two queries, ignoring the combining operators.
In addition to the operators described above, the ordinary B-tree comparison operators (=, <, etc) are defined 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.
get_current_ts_config()
Return type: regconfig
Get default text search configuration.
Example:
get_current_ts_config() english
length(tsvector)
Return type: integer
Number of lexemes in tsvector.
Example:
length('fat:2,4 cat:3 rat:5A'::tsvector)
3numnode(tsquery)
Return type: integer
Number of lexemes plus operators in tsquery.
Example:
numnode('(fat & rat) | cat'::tsquery)
5plainto_tsquery([ config regconfig , ] querytext)
Return type: tsquery
Produce tsquery ignoring punctuation.
Example:
plainto_tsquery('english', 'The Fat Rats')
'fat' & 'rat'querytree(query tsquery)
Return type: text
Get indexable part of a tsquery.
Example:
querytree('foo & ! bar'::tsquery)
'foo'setweight(tsvector, "char")
Return type: tsvector
Assign weight to each element of tsvector.
Example:
setweight('fat:2,4 cat:3 rat:5B'::tsvector, 'A')
'cat':3A 'fat':2A,4A 'rat':5Astrip(tsvector)
Return type: tsvector
Remove positions and weights from tsvector.
Example:
strip('fat:2,4 cat:3 rat:5A'::tsvector)
'cat' 'fat' 'rat'to_tsquery([ config regconfig , ] query text)
Return type: tsquery
Normalize words and convert to tsquery.
Example:
to_tsquery('english', 'The & Fat & Rats')
'fat' & 'rat'to_tsvector([ config regconfig , ] documenttext)
Return type: tsvector
Reduce document text to tsvector.
Example:
to_tsvector('english', 'The Fat Rats')
'fat':2 'rat':3ts_headline([ config regconfig, ] documenttext, query tsquery [, options text ])
Return type: text
Display a query match.
Example:
ts_headline('x y z', 'z'::tsquery)
x y <b>z</b>ts_rank([ weights float4[], ] vector tsvector,query tsquery [, normalization integer ])
Return type: float4
Rank document for query.
Example:
ts_rank(textsearch, query) 0.818
ts_rank_cd([ weights float4[], ] vectortsvector, query tsquery [, normalizationinteger ])
Return type: float4
Rank document for query using cover density.
Example:
ts_rank_cd('{0.1, 0.2, 0.4, 1.0}', textsearch, query)
2.01317ts_rewrite(query tsquery, target tsquery,substitute tsquery)
Return type: tsquery
Replace target with substitute within query.
Example:
ts_rewrite('a & b'::tsquery, 'a'::tsquery, 'foo | bar'::tsquery)
'b' & ( 'foo' | 'bar' )ts_rewrite(query tsquery, select text)
Return type: tsquery
Replace using targets and substitutes from a SELECT command.
Example:
SELECT ts_rewrite('a & b'::tsquery, 'SELECT t,s FROM aliases')
'b' & ( 'foo' | 'bar' )tsvector_update_trigger()
Return type: trigger
Trigger function for automatic tsvector column update.
Example:
CREATE TRIGGER ... tsvector_update_trigger(tsvcol, 'pg_catalog.swedish', title, body)
tsvector_update_trigger_column()
Return type: trigger
Trigger function for automatic tsvector column update.
Example:
CREATE TRIGGER ... tsvector_update_trigger_column(tsvcol, configcol, title, body)
Note All the text search functions that accept an optional
regconfigargument will use the configuration specified by default_text_search_config when that argument is omitted.
The following functions are listed separately because they are not usually used in everyday text searching operations. They are helpful for development and debugging of new text search configurations.
ts_debug([ configregconfig, ]documenttext, OUTaliastext, OUTdescriptiontext, OUTtokentext, OUTdictionariesregdictionary[], OUTdictionaryregdictionary, OUTlexemes text[])
Return type: setof record
Test a configuration.
Example:
ts_debug('english', 'The Brightest supernovaes')
(asciiword,"Word, all ASCII",The,{english_stem},english_stem,{}) ...ts_lexize(dictregdictionary,token text)
Return type: text[]
Test a dictionary.
Example:
ts_lexize('english_stem', 'stars')
{star}ts_parse(parser_nametext,documenttext, OUTtokidinteger, OUTtoken text)
Return type: setof record
Test a parser.
Example:
ts_parse('default', 'foo - bar')
(1,foo) ...ts_parse(parser_oidoid,documenttext, OUTtokidinteger, OUTtoken text)
Return type: setof record
Test a parser.
Example:
ts_parse(3722, 'foo - bar') (1,foo) ...
ts_token_type(parser_nametext, OUTtokidinteger, OUTalias text, OUT description text)
Return type: setof record
Get token types defined by parser.
Example:
ts_token_type('default')
(1,asciiword,"Word, all ASCII") ...ts_token_type(parser_oidoid, OUTtokidinteger, OUTaliastext, OUTdescription text)
Return type: setof record
Get token types defined by parser.
Example:
ts_token_type(3722) (1,asciiword,"Word, all ASCII") ...
ts_stat(sqlquerytext, [weightstext, ] OUTwordtext, OUTndocinteger, OUT nentry integer)
Return type: setof record
Get statistics of a tsvector column.
Example:
ts_stat('SELECT vector from apod')
(foo,10,15) ...Range Functions and Operators
See Range Types for an overview of range types.
The following operators are available for range types.
=
Equal.
Example:
int4range(1,5) = '[1,4]'::int4range t
<>
Not equal.
Example:
numrange(1.1,2.2) <> numrange(1.1,2.3) t
<
Less than.
Example:
int4range(1,10) < int4range(2,3) t
>
Greater than.
Example:
int4range(1,10) > int4range(1,5) t
<=
Less than or equal.
Example:
numrange(1.1,2.2) <= numrange(1.1,2.2) t
>=
Greater than or equal.
Example:
numrange(1.1,2.2) >= numrange(1.1,2.0) t
@> (contains range)
Example:
int4range(2,4) @> int4range(2,3) t
@> (contains element)
Example:
'[2011-01-01,2011-03-01)'::tsrange @> '2011-01-10'::timestamp t
<@ (range is contained by)
Example:
int4range(2,4) <@ int4range(1,7) t
<@ (element is contained by)
Example:
42 <@ int4range(1,7) f
&& (overlap)
Overlap, meaning the ranges have points in common.
Example:
int8range(3,7) && int8range(4,12) t
<< (strictly left of)
Example:
int8range(1,10) << int8range(100,110) t
>> (strictly right of)
Example:
int8range(50,60) >> int8range(20,30) t
&< (does not extend to the right of)
Example:
int8range(1,20) &< int8range(18,20) t
&> (does not extend to the left of)
Example:
int8range(7,20) &> int8range(5,10) t
-|- (is adjacent to)
Example:
numrange(1.1,2.2) -|- numrange(2.2,3.3) t
+ (union)
Example:
numrange(5,15) + numrange(10,20) [5,20)
* (intersection)
Example:
int8range(5,15) * int8range(10,20) [10,15)
- (difference)
Example:
int8range(5,15) - int8range(10,20) [5,10)
The simple comparison operators <, >, <=, and >= compare the lower bounds first, and only if those are equal, compare the upper bounds. These comparisons are not usually very useful for ranges, but are provided to allow B-tree indexes to be constructed on ranges.
The left-of/right-of/adjacent operators always return false when an empty range is involved; that is, an empty range is not considered to be either before or after any other range.
The union and difference operators will fail if the resulting range would need to contain two disjoint sub-ranges, as such a range cannot be represented.
The following functions are available for use with range types.
lower(anyrange)
Return type: range's element type
Lower bound of range.
Example:
lower(numrange(1.1,2.2)) 1.1
upper(anyrange)
Return type: range's element type
Upper bound of range.
Example:
upper(numrange(1.1,2.2)) 2.2
isempty(anyrange)
Return type: boolean
Is the range empty?
Example:
isempty(numrange(1.1,2.2)) false
lower_inc(anyrange)
Return type: boolean
Is the lower bound inclusive?
Example:
lower_inc(numrange(1.1,2.2)) true
upper_inc(anyrange)
Return type: boolean
Is the upper bound inclusive?
Example:
upper_inc(numrange(1.1,2.2)) false
lower_inf(anyrange)
Return type: boolean
Is the lower bound infinite?
Example:
lower_inf('(,)'::daterange)
trueupper_inf(anyrange)
Return type: boolean
Is the upper bound infinite?
Example:
upper_inf('(,)'::daterange)
truerange_merge(anyrange, anyrange)
Return type: anyrange
The smallest range which includes both of the given ranges.
Example:
range_merge('[1,2)'::int4range, '[3,4)'::int4range)
[1,4)The lower and upper functions return null if the range is empty or the requested bound is infinite. The lower_inc, upper_inc, lower_inf, and upper_inf functions all return false for an empty range.