This section describes: この節では次のことを説明します。
functions and operators for processing and creating JSON data JSONデータを処理、生成する関数と演算子
the SQL/JSON path language SQL/JSONパス言語
To provide native support for JSON data types within the SQL environment, <productname>PostgreSQL</productname> implements the <firstterm>SQL/JSON data model</firstterm>. This model comprises sequences of items. Each item can hold SQL scalar values, with an additional SQL/JSON null value, and composite data structures that use JSON arrays and objects. The model is a formalization of the implied data model in the JSON specification <ulink url="https://tools.ietf.org/html/rfc7159">RFC 7159</ulink>. SQL環境内のJSONデータ型にネイティブサポートを提供するために、PostgreSQLSQL/JSONデータモデルを実装しています。 このモデルは、一連の項目で構成されます。 各項目は、SQLスカラ値、追加のSQL/JSON NULL値、およびJSON配列とオブジェクトを使用する複合データ構造を保持できます。 モデルは、JSON指定RFC 7159で暗黙的に指定されているデータモデルを形式化したものです。
SQL/JSON allows you to handle JSON data alongside regular SQL data, with transaction support, including: SQL/JSONでは、トランザクションをサポートをしながら、通常のSQLデータと一緒にJSONデータをハンドルすることができます。以下のものが含まれます:
Uploading JSON data into the database and storing it in regular SQL columns as character or binary strings. JSONデータをデータベースにアップロードし、それを文字またはバイナリ文字列として通常のSQL列に保存します。
Generating JSON objects and arrays from relational data. リレーショナルデータからJSONオブジェクトと配列を生成します。
Querying JSON data using SQL/JSON query functions and SQL/JSON path language expressions. SQL/JSON問い合わせ関数およびSQL/JSONパス言語式を使用してJSONデータを照会します。
To learn more about the SQL/JSON standard, see <xref linkend="sqltr-19075-6"/>. For details on JSON types supported in <productname>PostgreSQL</productname>, see <xref linkend="datatype-json"/>. SQL/JSON標準を更に学ぶためには、[sqltr-19075-6]をご覧ください。 PostgreSQLでサポートされているJSON型の詳細に関しては、8.14をご覧ください。
<xref linkend="functions-json-op-table"/> shows the operators that
are available for use with JSON data types (see <xref
linkend="datatype-json"/>).
In addition, the usual comparison operators shown in <xref
linkend="functions-comparison-op-table"/> are available for
<type>jsonb</type>, though not for <type>json</type>. The comparison
operators follow the ordering rules for B-tree operations outlined in
<xref linkend="json-indexing"/>.
See also <xref linkend="functions-aggregate"/> for the aggregate
function <function>json_agg</function> which aggregates record
values as JSON, the aggregate function
<function>json_object_agg</function> which aggregates pairs of values
into a JSON object, and their <type>jsonb</type> equivalents,
<function>jsonb_agg</function> and <function>jsonb_object_agg</function>.
表 9.45にJSONデータ型(8.14を参照)で使用可能な演算子を示します。
加えて表 9.1で示す通常の比較演算子がjsonb
で利用できますが、json
では利用できません。
比較演算子は8.14.4で概要が示されているように示すBツリー操作用の順序付け規則にしたがいます。
レコードの値をJSONに集約するjson_agg
集約関数、値の対をJSONオブジェクトに集約するjson_object_agg
集約関数、およびそれらのjsonb
版のjsonb_agg
とjsonb_object_agg
については9.21も参照して下さい。
表9.45 json
とjsonb
演算子
Operator 演算子 Description 説明 Example(s) 例 |
---|
Extracts <parameter>n</parameter>'th element of JSON array
(array elements are indexed from zero, but negative integers count
from the end).
JSON配列の
|
Extracts JSON object field with the given key. 与えられたキーでJSONオブジェクトフィールドを取り出します。
|
Extracts <parameter>n</parameter>'th element of JSON array,
as <type>text</type>.
JSON配列の
|
Extracts JSON object field with the given key, as <type>text</type>.
与えられたキーでJSONオブジェクトフィールドを
|
Extracts JSON sub-object at the specified path, where path elements can be either field keys or array indexes. 指定したパスにおけるJSONの副オブジェクトを取り出します。パス要素はフィールドキーあるいは配列のインデックスでも構いません。
|
Extracts JSON sub-object at the specified path as <type>text</type>.
指定したパスにおけるJSONの副オブジェクトを
|
The field/element/path extraction operators return NULL, rather than failing, if the JSON input does not have the right structure to match the request; for example if no such key or array element exists. JSON入力が要求と一致する正しい構造をしていなければ、フィールド/要素/パス抽出演算子は失敗するのではなくNULLを返します。例えばそのような要素が存在しない場合です。
Some further operators exist only for <type>jsonb</type>, as shown
in <xref linkend="functions-jsonb-op-table"/>.
<xref linkend="json-indexing"/>
describes how these operators can be used to effectively search indexed
<type>jsonb</type> data.
ほかにjsonb
だけで利用可能な演算子もいくつか存在します。
それらを表 9.46に示します。
8.14.4には、インデックス付されたjsonb
データを効率的に検索するためにこれらの演算子をどのように利用できるかについて書いてあります。
表9.46 追加jsonb
演算子
Operator 演算子 Description 説明 Example(s) 例 |
---|
Does the first JSON value contain the second? (See <xref linkend="json-containment"/> for details about containment.) 最初のJSON値は二番目を含んでいるか? (包含の詳細は8.14.3を参照してください。)
|
Is the first JSON value contained in the second? 最初のJSON値は二番目に含まれているか?
|
Does the text string exist as a top-level key or array element within the JSON value? そのテキスト文字列はトップレベルのキーあるいは配列要素としてJSON値中に存在しているか?
|
Do any of the strings in the text array exist as top-level keys or array elements? テキスト配列中のどれかの文字列がトップレベルのキーあるいは配列要素として存在しているか?
|
Do all of the strings in the text array exist as top-level keys or array elements? テキスト配列のすべての文字列がトップレベルのキーあるいは配列要素として存在しているか?
|
Concatenates two <type>jsonb</type> values.
Concatenating two arrays generates an array containing all the
elements of each input. Concatenating two objects generates an
object containing the union of their
keys, taking the second object's value when there are duplicate keys.
All other cases are treated by converting a non-array input into a
single-element array, and then proceeding as for two arrays.
Does not operate recursively: only the top-level array or object
structure is merged.
2つの
To append an array to another array as a single entry, wrap it in an additional layer of array, for example: 一つの要素を持つとして配列を他の配列に追加するには、例のように配列の追加のレイヤー中に含めてください。
|
Deletes a key (and its value) from a JSON object, or matching string value(s) from a JSON array. キー(及びその値)をJSONオブジェクトから削除します。あるいはマッチする文字列値をJSON配列から削除します。
|
Deletes all matching keys or array elements from the left operand. 左のオペランドからマッチするすべてのキーあるいは配列要素を削除します。
|
Deletes the array element with specified index (negative integers count from the end). Throws an error if JSON value is not an array. 指定したインデックス(負の整数は最後から数えます)の配列要素を削除します。 JSON値が配列でなければエラーが生じます。
|
Deletes the field or array element at the specified path, where path elements can be either field keys or array indexes. 指定パスのフィールドあるいは配列要素を削除します。パス要素はフィールドキーあるいは配列インデックスが指定できます。
|
Does JSON path return any item for the specified JSON value? JSONパスは指定したJSON値の要素を返すか?
|
Returns the result of a JSON path predicate check for the
specified JSON value. Only the first item of the result is taken into
account. If the result is not Boolean, then <literal>NULL</literal>
is returned.
指定したJSON値に対するJSONパス述語チェックの結果を返します。
結果の最初の項目だけが考慮されます。
結果が論理値でなければ
|
The <type>jsonpath</type> operators <literal>@?</literal>
and <literal>@@</literal> suppress the following errors: missing object
field or array element, unexpected JSON item type, datetime and numeric
errors. The <type>jsonpath</type>-related functions described below can
also be told to suppress these types of errors. This behavior might be
helpful when searching JSON document collections of varying structure.
jsonpath
演算子の@?
および@@
演算子は以下のエラーを抑止します。
オブジェクトフィールドあるいは配列要素の欠如、期待しないJSON要素型、日付時刻及び数値エラー。
以下に示すjsonpath
関連の関数もこれらのエラーを抑止するようにすることもできます。
この振る舞いは、異なる構造のJSON文書集合を検索する際に役に立つかも知れません。
<xref linkend="functions-json-creation-table"/> shows the functions that are
available for constructing <type>json</type> and <type>jsonb</type> values.
表 9.47に、json
値およびjsonb
値を作成するために利用可能な関数を示します。
Some functions in this table have a <literal>RETURNING</literal> clause,
which specifies the data type returned. It must be one of <type>json</type>,
<type>jsonb</type>, <type>bytea</type>, a character string type (<type>text</type>,
<type>char</type>, <type>varchar</type>, or <type>nchar</type>), or a type
for which there is a cast from <type>json</type> to that type.
By default, the <type>json</type> type is returned.
このテーブルのいくつかの関数は、返却データ型を指定するRETURNING
句を伴います。
そのデータ型は、json
、jsonb
、bytea
、文字列型(text
、char
、varchar
、nchar
)、あるいはjson
からそれらの型へのキャストが存在する型でなければなりません。
デフォルトでは、json
型が返却されます。
表9.47 JSON作成関数
Function 関数 Description 説明 Example(s) 例 |
---|
Converts any SQL value to <type>json</type> or <type>jsonb</type>.
Arrays and composites are converted recursively to arrays and
objects (multidimensional arrays become arrays of arrays in JSON).
Otherwise, if there is a cast from the SQL data type
to <type>json</type>, the cast function will be used to perform the
conversion;<footnote>
SQL値を
|
Converts an SQL array to a JSON array. The behavior is the same
as <function>to_json</function> except that line feeds will be added
between top-level array elements if the optional boolean parameter is
true.
SQL配列をJSON配列に変換します。
追加の論理引数が真であるときに改行がトップレベルの配列要素の間に加えられる以外は、その振る舞いは
|
Constructs a JSON array from either a series of
<replaceable>value_expression</replaceable> parameters or from the results
of <replaceable>query_expression</replaceable>,
which must be a SELECT query returning a single column. If
<literal>ABSENT ON NULL</literal> is specified, NULL values are ignored.
This is always the case if a
<replaceable>query_expression</replaceable> is used.
JSON配列を、一連の
|
Converts an SQL composite value to a JSON object. The behavior is the
same as <function>to_json</function> except that line feeds will be
added between top-level elements if the optional boolean parameter is
true.
SQL複合値をJSONオブジェクトに変換します。
追加の論理引数が真であるときに改行がトップレベルの配列要素の間に加えられる以外は、その振る舞いは
|
Builds a possibly-heterogeneously-typed JSON array out of a variadic
argument list. Each argument is converted as
per <function>to_json</function> or <function>to_jsonb</function>.
異なる型から構成される可能性のあるJSON配列をvariadic引数リストから作成します。
各々の引数は
|
Builds a JSON object out of a variadic argument list. By convention,
the argument list consists of alternating keys and values. Key
arguments are coerced to text; value arguments are converted as
per <function>to_json</function> or <function>to_jsonb</function>.
variadic引数リストからJSONオブジェクトを作成します。
慣例により引数リストは代替キーと値が交互に並んだものです。
キー引数はテキストに強制的に変換されます。
値引数は
|
Constructs a JSON object of all the key/value pairs given,
or an empty object if none are given.
<replaceable>key_expression</replaceable> is a scalar expression
defining the <acronym>JSON</acronym> key, which is
converted to the <type>text</type> type.
It cannot be <literal>NULL</literal> nor can it
belong to a type that has a cast to the <type>json</type> type.
If <literal>WITH UNIQUE KEYS</literal> is specified, there must not
be any duplicate <replaceable>key_expression</replaceable>.
Any pair for which the <replaceable>value_expression</replaceable>
evaluates to <literal>NULL</literal> is omitted from the output
if <literal>ABSENT ON NULL</literal> is specified;
if <literal>NULL ON NULL</literal> is specified or the clause
omitted, the key is included with value <literal>NULL</literal>.
指定されたすべてのキー/値ペアのJSONオブジェクトを構築します。
キー/値ペアが指定されていない場合は、空のオブジェクトを構築します。
|
Builds a JSON object out of a text array. The array must have either exactly one dimension with an even number of members, in which case they are taken as alternating key/value pairs, or two dimensions such that each inner array has exactly two elements, which are taken as a key/value pair. All values are converted to JSON strings. テキスト配列からJSONオブジェクトを作成します。 配列は、偶数個の要素からなる1次元(キー/値の対が交互に並んでいるものと扱われます)あるいは内側の配列が2つの要素を持つ2次元(2つの要素がキー/値のペアとして扱われます)のいずれかでなければなりません。 すべての値はJSON文字列に変換されます。
|
This form of <function>json_object</function> takes keys and values
pairwise from separate text arrays. Otherwise it is identical to
the one-argument form.
この形の
|
[a]
For example, the <xref linkend="hstore"/> extension has a cast
from <type>hstore</type> to <type>json</type>, so that
<type>hstore</type> values converted via the JSON creation functions
will be represented as JSON objects, not as primitive string values.
たとえばhstore拡張には |
<xref linkend="functions-sqljson-misc" /> details SQL/JSON facilities for testing JSON. 表 9.48には、JSONをテストするためのSQL/JSON機能の詳細が記載されています。
表9.48 SQL/JSONテスト用関数
<xref linkend="functions-json-processing-table"/> shows the functions that
are available for processing <type>json</type> and <type>jsonb</type> values.
表 9.49にjson
とjsonb
値を処理するのに使える関数を示します。
表9.49 JSON処理関数
Function 関数 Description 説明 Example(s) 例 |
---|
Expands the top-level JSON array into a set of JSON values. トップレベルのJSON配列をJSON値の集合に展開します。
value ----------- 1 true [2,false]
|
Expands the top-level JSON array into a set of <type>text</type> values.
トップレベルのJSON配列を
value ----------- foo bar
|
Returns the number of elements in the top-level JSON array. トップレベルのJSON配列の要素数を返します。
|
Expands the top-level JSON object into a set of key/value pairs. トップレベルのJSONオブジェクトをキー/値のペアの集合に展開します。
key | value -----+------- a | "foo" b | "bar"
|
Expands the top-level JSON object into a set of key/value pairs.
The returned <parameter>value</parameter>s will be of
type <type>text</type>.
トップレベルのJSONオブジェクトをキー/値のペアの集合に展開します。
返り値の
key | value -----+------- a | foo b | bar
|
Extracts JSON sub-object at the specified path.
(This is functionally equivalent to the <literal>#></literal>
operator, but writing the path out as a variadic list can be more
convenient in some cases.)
指定したパスにおけるJSONの副オブジェクトを取り出します。
(これは
|
Extracts JSON sub-object at the specified path as <type>text</type>.
(This is functionally equivalent to the <literal>#>></literal>
operator.)
指定したパスにおけるJSONの副オブジェクトを
|
Returns the set of keys in the top-level JSON object. トップレベルのJSONオブジェクト中のキーの集合を返します。
json_object_keys ------------------ f1 f2
|
Expands the top-level JSON object to a row having the composite type
of the <parameter>base</parameter> argument. The JSON object
is scanned for fields whose names match column names of the output row
type, and their values are inserted into those columns of the output.
(Fields that do not correspond to any output column name are ignored.)
In typical use, the value of <parameter>base</parameter> is just
<literal>NULL</literal>, which means that any output columns that do
not match any object field will be filled with nulls. However,
if <parameter>base</parameter> isn't <literal>NULL</literal> then
the values it contains will be used for unmatched columns.
トップレベルのJSONオブジェクトを To convert a JSON value to the SQL type of an output column, the following rules are applied in sequence: JSON値を出力列のSQL型に変換する際に以下のルールが順に適用されます。
While the example below uses a constant JSON value, typical use would
be to reference a <type>json</type> or <type>jsonb</type> column
laterally from another table in the query's <literal>FROM</literal>
clause. Writing <function>json_populate_record</function> in
the <literal>FROM</literal> clause is good practice, since all of the
extracted columns are available for use without duplicate function
calls.
これらの関数の例ではJSON定数を使用していますが、典型的な使用法はその
a | b | c ---+-----------+------------- 1 | {2,"a b"} | (4,"a b c")
|
Expands the top-level JSON array of objects to a set of rows having
the composite type of the <parameter>base</parameter> argument.
Each element of the JSON array is processed as described above
for <function>json[b]_populate_record</function>.
トップレベルのJSONオブジェクトを
a | b ---+--- 1 | 2 3 | 4
|
Expands the top-level JSON object to a row having the composite type
defined by an <literal>AS</literal> clause. (As with all functions
returning <type>record</type>, the calling query must explicitly
define the structure of the record with an <literal>AS</literal>
clause.) The output record is filled from fields of the JSON object,
in the same way as described above
for <function>json[b]_populate_record</function>. Since there is no
input record value, unmatched columns are always filled with nulls.
トップレベルのJSONオブジェクトを
a | b | c | d | r ---+---------+---------+---+--------------- 1 | [1,2,3] | {1,2,3} | | (123,"a b c")
|
Expands the top-level JSON array of objects to a set of rows having
the composite type defined by an <literal>AS</literal> clause. (As
with all functions returning <type>record</type>, the calling query
must explicitly define the structure of the record with
an <literal>AS</literal> clause.) Each element of the JSON array is
processed as described above
for <function>json[b]_populate_record</function>.
トップレベルのJSON配列を
a | b ---+----- 1 | foo 2 |
|
Returns <parameter>target</parameter>
with the item designated by <parameter>path</parameter>
replaced by <parameter>new_value</parameter>, or with
<parameter>new_value</parameter> added if
<parameter>create_if_missing</parameter> is true (which is the
default) and the item designated by <parameter>path</parameter>
does not exist.
All earlier steps in the path must exist, or
the <parameter>target</parameter> is returned unchanged.
As with the path oriented operators, negative integers that
appear in the <parameter>path</parameter> count from the end
of JSON arrays.
If the last path step is an array index that is out of range,
and <parameter>create_if_missing</parameter> is true, the new
value is added at the beginning of the array if the index is negative,
or at the end of the array if it is positive.
|
If <parameter>new_value</parameter> is not <literal>NULL</literal>,
behaves identically to <literal>jsonb_set</literal>. Otherwise behaves
according to the value
of <parameter>null_value_treatment</parameter> which must be one
of <literal>'raise_exception'</literal>,
<literal>'use_json_null'</literal>, <literal>'delete_key'</literal>, or
<literal>'return_target'</literal>. The default is
<literal>'use_json_null'</literal>.
|
Returns <parameter>target</parameter>
with <parameter>new_value</parameter> inserted. If the item
designated by the <parameter>path</parameter> is an array
element, <parameter>new_value</parameter> will be inserted before
that item if <parameter>insert_after</parameter> is false (which
is the default), or after it
if <parameter>insert_after</parameter> is true. If the item
designated by the <parameter>path</parameter> is an object
field, <parameter>new_value</parameter> will be inserted only if
the object does not already contain that key.
All earlier steps in the path must exist, or
the <parameter>target</parameter> is returned unchanged.
As with the path oriented operators, negative integers that
appear in the <parameter>path</parameter> count from the end
of JSON arrays.
If the last path step is an array index that is out of range, the new
value is added at the beginning of the array if the index is negative,
or at the end of the array if it is positive.
|
Deletes all object fields that have null values from the given JSON value, recursively. Null values that are not object fields are untouched. 与えられたJSON値からNULLを持つオブジェクトフィールドをすべて削除します。 オブジェクトフィールドではないNULL値は変わりません。
|
Checks whether the JSON path returns any item for the specified JSON
value.
If the <parameter>vars</parameter> argument is specified, it must
be a JSON object, and its fields provide named values to be
substituted into the <type>jsonpath</type> expression.
If the <parameter>silent</parameter> argument is specified and
is <literal>true</literal>, the function suppresses the same errors
as the <literal>@?</literal> and <literal>@@</literal> operators do.
JSONパスが指定したJSON値に対して項目を返すかどうかをチェックします。
|
Returns the result of a JSON path predicate check for the specified
JSON value. Only the first item of the result is taken into account.
If the result is not Boolean, then <literal>NULL</literal> is returned.
The optional <parameter>vars</parameter>
and <parameter>silent</parameter> arguments act the same as
for <function>jsonb_path_exists</function>.
指定したJSON値のJSONパス述語チェックの結果を返します。
結果の最初の項目だけが考慮されます。
結果がBooleanでないなら、
|
Returns all JSON items returned by the JSON path for the specified
JSON value.
The optional <parameter>vars</parameter>
and <parameter>silent</parameter> arguments act the same as
for <function>jsonb_path_exists</function>.
JSON値に対するJSONパスによって返されるすべてのJSON項目を返します。
オプションの
jsonb_path_query ------------------ 2 3 4
|
Returns all JSON items returned by the JSON path for the specified
JSON value, as a JSON array.
The optional <parameter>vars</parameter>
and <parameter>silent</parameter> arguments act the same as
for <function>jsonb_path_exists</function>.
JSON値に対するJSONパスによって返されるすべてのJSON項目をJSON配列として返します。
オプションの
|
Returns the first JSON item returned by the JSON path for the
specified JSON value. Returns <literal>NULL</literal> if there are no
results.
The optional <parameter>vars</parameter>
and <parameter>silent</parameter> arguments act the same as
for <function>jsonb_path_exists</function>.
JSON値に対するJSONパスによって返される最初のJSON項目を返します。
結果がなければ
|
These functions act like their counterparts described above without
the <literal>_tz</literal> suffix, except that these functions support
comparisons of date/time values that require timezone-aware
conversions. The example below requires interpretation of the
date-only value <literal>2015-08-02</literal> as a timestamp with time
zone, so the result depends on the current
<xref linkend="guc-timezone"/> setting. Due to this dependency, these
functions are marked as stable, which means these functions cannot be
used in indexes. Their counterparts are immutable, and so can be used
in indexes; but they will throw errors if asked to make such
comparisons.
これらの関数は、時間帯を考慮する日時値の比較をサポートすることを除いて、上で述べた、
|
Converts the given JSON value to pretty-printed, indented text. 与えられたJSON値を整形されたインデント付きテキストに変換します。
[ { "f1": 1, "f2": null }, 2 ]
|
Returns the type of the top-level JSON value as a text string.
Possible types are
<literal>object</literal>, <literal>array</literal>,
<literal>string</literal>, <literal>number</literal>,
<literal>boolean</literal>, and <literal>null</literal>.
(The <literal>null</literal> result should not be confused
with an SQL NULL; see the examples.)
トップレベルのJSON値の型をテキスト文字列として返します。
可能な型は次のとおりです。
|
SQL/JSON path expressions specify the items to be retrieved
from the JSON data, similar to XPath expressions used
for SQL access to XML. In <productname>PostgreSQL</productname>,
path expressions are implemented as the <type>jsonpath</type>
data type and can use any elements described in
<xref linkend="datatype-jsonpath"/>.
SQL/JSONパス式は、XMLへのSQLアクセスで使用されるXPath同様、JSONデータから取り出す項目を指定します。
PostgreSQLではパス式はjsonpath
データ型として実装されており、8.14.7で説明されているすべての要素を使うことができます。
JSON query functions and operators pass the provided path expression to the <firstterm>path engine</firstterm> for evaluation. If the expression matches the queried JSON data, the corresponding JSON item, or set of items, is returned. Path expressions are written in the SQL/JSON path language and can include arithmetic expressions and functions. JSON問い合わせ関数と演算子は与えられたパス式をpath engineに渡して評価します。 式が問い合わせ対象のJSONデータにマッチすれば、関連するSQL/JSON項目が返却されます。 パス式はSQL/JSONパス言語で書かれ、算術式と関数を含むことができます。
A path expression consists of a sequence of elements allowed
by the <type>jsonpath</type> data type.
The path expression is normally evaluated from left to right, but
you can use parentheses to change the order of operations.
If the evaluation is successful, a sequence of JSON items is produced,
and the evaluation result is returned to the JSON query function
that completes the specified computation.
パス式はjsonpath
データ型で認められた一連の要素からなります。
パス式は通常左から右へと評価されますが、括弧を使って演算の順序を変更することができます。
評価が成功すれば、一連のJSON項目が生成され、評価結果が指定した計算を完了したJSON問い合わせ関数に戻されます。
To refer to the JSON value being queried (the
<firstterm>context item</firstterm>), use the <literal>$</literal> variable
in the path expression. It can be followed by one or more
<link linkend="type-jsonpath-accessors">accessor operators</link>,
which go down the JSON structure level by level to retrieve sub-items
of the context item. Each operator that follows deals with the
result of the previous evaluation step.
問い合わせ対象(context item)のJSONデータを参照するには、パス式内で$
値を使います。
複数のアクセサ演算子をその後に記述することもできます。
それによってJSON構造をレベル順に訪れて文脈項目の副項目の内容を取り出します。
後続の個々の演算子はその前の評価段階の結果を処理します。
For example, suppose you have some JSON data from a GPS tracker that you would like to parse, such as: たとえば、次のようなパースしたいGPSトラッカーからのJSONデータがあるとします。
{ "track": { "segments": [ { "location": [ 47.763, 13.4034 ], "start time": "2018-10-14 10:05:14", "HR": 73 }, { "location": [ 47.706, 13.2635 ], "start time": "2018-10-14 10:39:21", "HR": 135 } ] } }
To retrieve the available track segments, you need to use the
<literal>.<replaceable>key</replaceable></literal> accessor
operator to descend through surrounding JSON objects:
存在するトラックセグメントを取り出すには、.
アクセサ演算子を使用して、周辺のJSONオブジェクトを下っていく必要があります。
key
$.track.segments
To retrieve the contents of an array, you typically use the
<literal>[*]</literal> operator. For example,
the following path will return the location coordinates for all
the available track segments:
配列の内容を取り出すには、典型的には[*]
演算子を使います。
たとえば次のパスはすべての存在するトラックセグメントの位置座標を返します。
$.track.segments[*].location
To return the coordinates of the first segment only, you can
specify the corresponding subscript in the <literal>[]</literal>
accessor operator. Recall that JSON array indexes are 0-relative:
最初のセグメントの座標だけを返すには、[]
アクセサ演算子の中で対応する添え字を指定することができます。
JSON配列インデックスは0スタートであることに注意してください。
$.track.segments[0].location
The result of each path evaluation step can be processed
by one or more <type>jsonpath</type> operators and methods
listed in <xref linkend="functions-sqljson-path-operators"/>.
Each method name must be preceded by a dot. For example,
you can get the size of an array:
各段階でのパス評価結果は9.16.2.2に列挙されている一つ以上のjsonpath
演算子とメソッドで処理することができます。
各々のメソッド名の前にピリオドを付けなければなりません。
たとえば配列の大きさを得ることができます。
$.track.segments.size()
More examples of using <type>jsonpath</type> operators
and methods within path expressions appear below in
<xref linkend="functions-sqljson-path-operators"/>.
パス式内のjsonpath
演算子とメソッドを使用する他の例については以下の9.16.2.2を参照してください。
When defining a path, you can also use one or more
<firstterm>filter expressions</firstterm> that work similarly to the
<literal>WHERE</literal> clause in SQL. A filter expression begins with
a question mark and provides a condition in parentheses:
パスを定義する際にはSQLのWHERE
節のように働く一つ以上のフィルター式が利用できます。
フィルター式はクェスチョンマークで始まり、カッコ内に条件を記述します。
? (condition
)
Filter expressions must be written just after the path evaluation step
to which they should apply. The result of that step is filtered to include
only those items that satisfy the provided condition. SQL/JSON defines
three-valued logic, so the condition can be <literal>true</literal>, <literal>false</literal>,
or <literal>unknown</literal>. The <literal>unknown</literal> value
plays the same role as SQL <literal>NULL</literal> and can be tested
for with the <literal>is unknown</literal> predicate. Further path
evaluation steps use only those items for which the filter expression
returned <literal>true</literal>.
フィルター式はそれを適用するパス評価段階の直後に指定しなければなりません。
この段階の結果は、指定した条件を満たす項目だけが含まれるようにフィルターされます。
SQL/JSONは3値論理を定義しており、条件はtrue
、false
、unknown
のどれかです。
unknown
は値はSQLのNULL
と同じ役割を果たし、is unknown
述語で評価できます。
その後の評価段階ではtrue
を返すフィルター式に対応する項目だけが使われます。
The functions and operators that can be used in filter expressions are
listed in <xref linkend="functions-sqljson-filter-ex-table"/>. Within a
filter expression, the <literal>@</literal> variable denotes the value
being filtered (i.e., one result of the preceding path step). You can
write accessor operators after <literal>@</literal> to retrieve component
items.
フィルター式内で利用できる関数と演算子は表 9.51にリストされています。
フィルター式内では、フィルターする必要のある値は@
変数で示します。(つまり以前のパスステップの結果の一つです。)
コンポーネント項目を取得するためにアクセサ演算子を@
の後に記述することができます。
For example, suppose you would like to retrieve all heart rate values higher than 130. You can achieve this using the following expression: たとえば130より高いすべての心拍数を取り出したいとします。次の式を使ってそれを得ることができます。
$.track.segments[*].HR ? (@ > 130)
To get the start times of segments with such values, you have to filter out irrelevant segments before returning the start times, so the filter expression is applied to the previous step, and the path used in the condition is different: そうした値を持つセグメントの開始時刻を得たい場合は、開始時刻を返す前に無関係のセグメントを取り除く必要があります。 そうすることにより前の段階にフィルター式が適用されるので、その条件で適用されるパスは異なります。
$.track.segments[*] ? (@.HR > 130)."start time"
You can use several filter expressions in sequence, if required. For example, the following expression selects start times of all segments that contain locations with relevant coordinates and high heart rate values: 必要なら複数のフィルター式を順に使用することができます。 たとえば次の式は指定した座標と高い心拍数値を持つ位置を持つすべてのセグメントを選択します。
$.track.segments[*] ? (@.location[1] < 13.4) ? (@.HR > 130)."start time"
Using filter expressions at different nesting levels is also allowed. The following example first filters all segments by location, and then returns high heart rate values for these segments, if available: 異なる入れ子レベルに対してフィルター式を適用することもできます。 次の例では、まず位置ですべてのセグメントをフィルターし、もしあれば高い心拍数値を返します。
$.track.segments[*] ? (@.location[1] < 13.4).HR ? (@ > 130)
You can also nest filter expressions within each other: フィルター式をお互いに入れ子にすることもできます。
$.track ? (exists(@.segments[*] ? (@.HR > 130))).segments.size()
This expression returns the size of the track if it contains any segments with high heart rate values, or an empty sequence otherwise. この式は高い心拍数値を含むトラックがあればそのすべてのサイズを返します。もしなければ空のシーケンスが返ります。
<productname>PostgreSQL</productname>'s implementation of the SQL/JSON path language has the following deviations from the SQL/JSON standard: PostgreSQLのSQL/JSONパス言語の実装はSQL/JSON標準と次の点が異なります。
A path expression can be a Boolean predicate, although the SQL/JSON
standard allows predicates only in filters. This is necessary for
implementation of the <literal>@@</literal> operator. For example,
the following <type>jsonpath</type> expression is valid in
<productname>PostgreSQL</productname>:
SQL/JSON標準ではフィルター内でのみ述語が使えますが、パス式はBoolean述語でも構いません。
これは@@
演算子を実装するために必要です。
たとえば、次のjsonpath
式はPostgreSQLでは有効です。
$.track.segments[*].HR < 70
There are minor differences in the interpretation of regular
expression patterns used in <literal>like_regex</literal> filters, as
described in <xref linkend="jsonpath-regular-expressions"/>.
9.16.2.3で述べるように、like_regex
フィルターで使用される正規表現パターンの解釈には些細な違いがあります。
When you query JSON data, the path expression may not match the actual JSON data structure. An attempt to access a non-existent member of an object or element of an array results in a structural error. SQL/JSON path expressions have two modes of handling structural errors: JSONデータを問い合わせる際、パス式は実際のJSONデータ構造に一致しないかも知れません。 存在しないオブジェクトのメンバーあるいは配列要素にアクセスしようとすると、構造上のエラーとなります。 SQL/JSONパス式には構造上のエラーを扱うための2つのモードがあります。
lax (default) — the path engine implicitly adapts the queried data to the specified path. Any remaining structural errors are suppressed and converted to empty SQL/JSON sequences. 非厳密(lax)モード(デフォルト)— パスエンジンは指定したパスを問い合わせデータに暗黙的に適合させます。 構造上のエラーは抑止され、空のSQL/JSONシーケンスへと変換されます。
strict — if a structural error occurs, an error is raised. 厳密(strict)モード — 構造上のエラーがあるとエラーが発生します。
The lax mode facilitates matching of a JSON document structure and path expression if the JSON data does not conform to the expected schema. If an operand does not match the requirements of a particular operation, it can be automatically wrapped as an SQL/JSON array or unwrapped by converting its elements into an SQL/JSON sequence before performing this operation. Besides, comparison operators automatically unwrap their operands in the lax mode, so you can compare SQL/JSON arrays out-of-the-box. An array of size 1 is considered equal to its sole element. Automatic unwrapping is not performed only when: 非厳密モードは、JSONデータが期待されるスキーマに沿わないときにJSON文書構造とパス式のマッチングを助けます。 あるオペランドが操作の要件に合わないときにはそれをSQL/JSON配列にまとめたり、あるいは操作を行う前にそれをSQL/JSONシーケンスに展開することもできます。 また非厳密モードにおいては、比較演算子は自動的にオペランドを展開し、SQL/JSON配列をそのまま比較することができます。 大きさ1の配列はその単独要素と同じものとして扱われます。 自動展開は以下の場合にのみ行われません。
The path expression contains <literal>type()</literal> or
<literal>size()</literal> methods that return the type
and the number of elements in the array, respectively.
それぞれ配列の型、要素数を返すtype()
、size()
をパス式が含む。
The queried JSON data contain nested arrays. In this case, only the outermost array is unwrapped, while all the inner arrays remain unchanged. Thus, implicit unwrapping can only go one level down within each path evaluation step. 問い合わせ対象のJSONデータが入れ子の配列を含む。 この場合はもっとも外側の配列のみが展開され、内側の配列は変わりません。 ですから、それぞれの評価段階において1レベルのみに暗黙的な展開が行われます。
For example, when querying the GPS data listed above, you can abstract from the fact that it stores an array of segments when using the lax mode: たとえば、上述のGPSデータに問い合わせする際、非厳密モードでは配列のセグメントを含んでいることを抽象化できます。
lax $.track.segments.location
In the strict mode, the specified path must exactly match the structure of
the queried JSON document to return an SQL/JSON item, so using this
path expression will cause an error. To get the same result as in
the lax mode, you have to explicitly unwrap the
<literal>segments</literal> array:
厳密モードでは、指定したパスはSQL/JSON項目を返す問い合わせ対象のJSON文書の構造に正確に一致していなければなりません。ですから、このパス式を使うとエラーになります。
非厳密モードと同じ結果を得るためには、segments
配列を明示的に展開する必要があります。
strict $.track.segments[*].location
The <literal>.**</literal> accessor can lead to surprising results
when using the lax mode. For instance, the following query selects every
<literal>HR</literal> value twice:
.**
アクセサを非厳密モードで使うと驚くべき結果をもたらすことがあります。
たとえば、次の問い合わせはすべてのHR
値を2回検索します。
lax $.**.HR
This happens because the <literal>.**</literal> accessor selects both
the <literal>segments</literal> array and each of its elements, while
the <literal>.HR</literal> accessor automatically unwraps arrays when
using the lax mode. To avoid surprising results, we recommend using
the <literal>.**</literal> accessor only in the strict mode. The
following query selects each <literal>HR</literal> value just once:
これは.**
アクセサがsegments
とその各々の要素の両方を検索するからです。
一方、.HR
アクセサは非厳密モードでは自動的に配列を展開します。
予期しない結果を避けるには、.**
アクセサを厳密モードでのみ使うことをお勧めします。
次の問い合わせはHR
の各値を一度だけ検索します。
strict $.**.HR
<xref linkend="functions-sqljson-op-table"/> shows the operators and
methods available in <type>jsonpath</type>. Note that while the unary
operators and methods can be applied to multiple values resulting from a
preceding path step, the binary operators (addition etc.) can only be
applied to single values.
表 9.50にjsonpath
で利用可能な演算子とメソッドを示します。
単項演算子とメソッドは以前のパスステップから生じた複数の値に適用できますが、二項演算子(加算など)は単一の値にしか適用できないことに注意してください。
表9.50 jsonpath
演算子とメソッド
Operator/Method 演算子/メソッド Description 説明 Example(s) 例 |
---|
Addition 加算
|
Unary plus (no operation); unlike addition, this can iterate over multiple values 単項のプラス(演算なし)。加算と違って、複数の値に渡って適用できます。
|
Subtraction 減算
|
Negation; unlike subtraction, this can iterate over multiple values 負符号。減算と違って、複数の値に渡って適用できます。
|
Multiplication 乗算
|
Division 除算
|
Modulo (remainder) 剰余(残り)
|
Type of the JSON item (see <function>json_typeof</function>)
JSON項目の型(
|
Size of the JSON item (number of array elements, or 1 if not an array) JSON項目の大きさ(配列の要素数。配列でなければ1)
|
Approximate floating-point number converted from a JSON number or string JSON数値あるいは文字列から変換した概算の浮動小数点数
|
Nearest integer greater than or equal to the given number 引数より大きいか等しく、与えられた数に最も近い整数
|
Nearest integer less than or equal to the given number 引数より小さいか等しく、与えられた数に最も近い整数
|
Absolute value of the given number 与えられた数の絶対値
|
Date/time value converted from a string 文字列から変換した日時値
|
Date/time value converted from a string using the
specified <function>to_timestamp</function> template
指定の
|
The object's key-value pairs, represented as an array of objects
containing three fields: <literal>"key"</literal>,
<literal>"value"</literal>, and <literal>"id"</literal>;
<literal>"id"</literal> is a unique identifier of the object the
key-value pair belongs to
以下の3つのフィールドを含むオブジェクトの配列で表現したオブジェクトのキー/値ペア。
|
The result type of the <literal>datetime()</literal> and
<literal>datetime(<replaceable>template</replaceable>)</literal>
methods can be <type>date</type>, <type>timetz</type>, <type>time</type>,
<type>timestamptz</type>, or <type>timestamp</type>.
Both methods determine their result type dynamically.
datetime()
とdatetime(
の結果型はtemplate
)date
、timetz
、time
、timestamptz
、あるいはtimestamp
です。
両方のメソッドは結果型を動的に決定します。
The <literal>datetime()</literal> method sequentially tries to
match its input string to the ISO formats
for <type>date</type>, <type>timetz</type>, <type>time</type>,
<type>timestamptz</type>, and <type>timestamp</type>. It stops on
the first matching format and emits the corresponding data type.
datetime()
メソッドは入力文字列をdate
、timetz
、time
、timestamptz
、timestamp
のISO形式に対して順にマッチを試みます。
最初にマッチした形式で停止し、関連するデータ型を出力します。
The <literal>datetime(<replaceable>template</replaceable>)</literal>
method determines the result type according to the fields used in the
provided template string.
datetime(
メソッドは与えられたテンプレート文字列にあるフィールドに従って結果型を決定します。
template
)
The <literal>datetime()</literal> and
<literal>datetime(<replaceable>template</replaceable>)</literal> methods
use the same parsing rules as the <literal>to_timestamp</literal> SQL
function does (see <xref linkend="functions-formatting"/>), with three
exceptions. First, these methods don't allow unmatched template
patterns. Second, only the following separators are allowed in the
template string: minus sign, period, solidus (slash), comma, apostrophe,
semicolon, colon and space. Third, separators in the template string
must exactly match the input string.
datetime()
とdatetime(
はtemplate
)to_timestamp
SQL関数と同じ解析ルール(参照9.8)を用いますが、3つの例外があります。
一番目に、これらのメソッドは一致しないテンプレートパターンを許容しません。二番目に次の区切り文字のみを許容します。負符号、ピリオド、斜線(スラッシュ)、カンマ、アポストロフィー、セミコロン、コロン、空白、です。
三番目にテンプレート文字列中の区切り文字は正確に入力文字列と一致しなければなりません。
If different date/time types need to be compared, an implicit cast is
applied. A <type>date</type> value can be cast to <type>timestamp</type>
or <type>timestamptz</type>, <type>timestamp</type> can be cast to
<type>timestamptz</type>, and <type>time</type> to <type>timetz</type>.
However, all but the first of these conversions depend on the current
<xref linkend="guc-timezone"/> setting, and thus can only be performed
within timezone-aware <type>jsonpath</type> functions.
異なる日時型の比較が必要なら、暗黙的なキャストが適用されます。
date
値はtimestamp
あるいはtimestamptz
にキャストできます。
timestamp
はtimestamptz
に、time
はtimetz
にキャストできます。
しかし、これらの変換の最初のものは現在のTimeZone設定に依存します。ですから時間帯を認識するjsonpath
関数中でのみ実行可能です。
<xref linkend="functions-sqljson-filter-ex-table"/> shows the available filter expression elements. 表 9.51に利用可能なフィルター式要素を示します。
表9.51 jsonpath
フィルター式要素
Predicate/Value 述語/値 Description 説明 Example(s) 例 |
---|
Equality comparison (this, and the other comparison operators, work on all JSON scalar values) 等値比較(これと他の比較演算子はすべてのJSONスカラー値で使えます)
|
Non-equality comparison 非等値比較
|
Less-than comparison 未満比較
|
Less-than-or-equal-to comparison 以下比較
|
Greater-than comparison より大きい比較
|
Greater-than-or-equal-to comparison 以上比較
|
JSON constant <literal>true</literal>
JSON定数
|
JSON constant <literal>false</literal>
JSON定数
|
JSON constant <literal>null</literal> (note that, unlike in SQL,
comparison to <literal>null</literal> works normally)
JSON定数
|
Boolean AND 論理AND
|
Boolean OR 論理OR
|
Boolean NOT 論理NOT
|
Tests whether a Boolean condition is <literal>unknown</literal>.
論理条件が
|
Tests whether the first operand matches the regular expression
given by the second operand, optionally with modifications
described by a string of <literal>flag</literal> characters (see
<xref linkend="jsonpath-regular-expressions"/>).
最初のオペランドが2番目のオペランドで与えられる正規表現にマッチするかどうか検査します。
オプションで
|
Tests whether the second operand is an initial substring of the first operand. 2番目の文字列が1番目のオペランドの最初の部分文字列かどうかを検査します。
|
Tests whether a path expression matches at least one SQL/JSON item.
Returns <literal>unknown</literal> if the path expression would result
in an error; the second example uses this to avoid a no-such-key error
in strict mode.
パス式が少なくとも一つのSQL/JSON項目とマッチするかどうかを検査します。
パス式がエラーとなる場合は
|
SQL/JSON path expressions allow matching text to a regular expression
with the <literal>like_regex</literal> filter. For example, the
following SQL/JSON path query would case-insensitively match all
strings in an array that start with an English vowel:
SQL/JSONパス式ではlike_regex
フィルターを使ってテキストを正規表現にマッチさせることができます。
たとえば、次のSQL/JSONパス式問い合わせは、英語の母音で始まる配列内のすべての文字列に大文字小文字を無視してマッチするでしょう。
$[*] ? (@ like_regex "^[aeiou]" flag "i")
The optional <literal>flag</literal> string may include one or more of
the characters
<literal>i</literal> for case-insensitive match,
<literal>m</literal> to allow <literal>^</literal>
and <literal>$</literal> to match at newlines,
<literal>s</literal> to allow <literal>.</literal> to match a newline,
and <literal>q</literal> to quote the whole pattern (reducing the
behavior to a simple substring match).
オプションのflag
文字列は一つ以上の文字を含むことができます。
i
は大文字小文字を無視したマッチ、m
は^
と$
で改行にマッチ、s
は.
が改行にマッチ、q
はパターン全体を参照します。(振る舞いを単純な部分文字列マッチとします)
The SQL/JSON standard borrows its definition for regular expressions
from the <literal>LIKE_REGEX</literal> operator, which in turn uses the
XQuery standard. PostgreSQL does not currently support the
<literal>LIKE_REGEX</literal> operator. Therefore,
the <literal>like_regex</literal> filter is implemented using the
POSIX regular expression engine described in
<xref linkend="functions-posix-regexp"/>. This leads to various minor
discrepancies from standard SQL/JSON behavior, which are cataloged in
<xref linkend="posix-vs-xquery"/>.
Note, however, that the flag-letter incompatibilities described there
do not apply to SQL/JSON, as it translates the XQuery flag letters to
match what the POSIX engine expects.
SQL/JSON標準は正規表現の定義を、XQuery標準を使用するLIKE_REGEX
演算子から借りています。
PostgreSQLは今の所LIKE_REGEX
演算子をサポートしていません。
ですから、like_regex
フィルターは9.7.3で説明されているPOSIX正規表現で実装されています。
このことにより、9.7.3.8で列挙されているSQL/JSON標準の振る舞いとの小さな違いが生じます。
しかし、ここで述べているフラグ文字の非互換性はSQL/JSONには適用されないことに注意してください。SQL/JSONは、XQueryのフラグ文字をPOSIXエンジンが期待するのと一致するように解釈するからです。
Keep in mind that the pattern argument of <literal>like_regex</literal>
is a JSON path string literal, written according to the rules given in
<xref linkend="datatype-jsonpath"/>. This means in particular that any
backslashes you want to use in the regular expression must be doubled.
For example, to match string values of the root document that contain
only digits:
like_regex
のパターン引数は8.14.7で説明されているルールにしたがって書かれたJSONパス文字列リテラルであることに注意してください。
これは、正規表現で使用するすべてのバックスラッシュを二重に書かなければならないことを意味します。
たとえば、数字のみを含むroot文書の文字列値にマッチさせるには以下のようにします。
$.* ? (@ like_regex "^\\d+$")