バージョンごとのドキュメント一覧

8.14. JSONデータ型 #

<title><acronym>JSON</acronym> Types</title>

JSON data types are for storing JSON (JavaScript Object Notation) data, as specified in <ulink url="https://tools.ietf.org/html/rfc7159">RFC 7159</ulink>. Such data can also be stored as <type>text</type>, but the JSON data types have the advantage of enforcing that each stored value is valid according to the JSON rules. There are also assorted JSON-specific functions and operators available for data stored in these data types; see <xref linkend="functions-json"/>. JSONデータ型はJSON(JavaScript Object Notation)データを格納するためのものです。JSONの仕様はRFC 7159に定義されています。 このようなデータは、text型として格納することもできますが、JSONデータ型は、それぞれ格納された値がJSONルールに従って有効に施行されるという利点があります。 これらのデータ型に格納されたデータのために利用可能な各種JSON固有の関数と演算子もあります。 9.16を参照してください。

<productname>PostgreSQL</productname> offers two types for storing JSON data: <type>json</type> and <type>jsonb</type>. To implement efficient query mechanisms for these data types, <productname>PostgreSQL</productname> also provides the <type>jsonpath</type> data type described in <xref linkend="datatype-jsonpath"/>. PostgreSQLには、JSONデータを格納するための2つの型、jsonjsonbがあります。 これらのデータ型に対して効率的な問い合わせメカニズムを実装するために、PostgreSQL8.14.7で説明されているjsonpathデータ型も提供します。

The <type>json</type> and <type>jsonb</type> data types accept <emphasis>almost</emphasis> identical sets of values as input. The major practical difference is one of efficiency. The <type>json</type> data type stores an exact copy of the input text, which processing functions must reparse on each execution; while <type>jsonb</type> data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed. <type>jsonb</type> also supports indexing, which can be a significant advantage. json型とjsonb型というデータ型は、ほとんど 同一の入力値セットを受け入れます。 現実的に主要な違いは効率です。 jsonデータ型は入力テキストの正確なコピーで格納し、処理関数を実行するたびに再解析する必要があります。 jsonbデータ型では、分解されたバイナリ形式で格納されます。 格納するときには変換のオーバーヘッドのため少し遅くなりますが、処理するときには、全く再解析が必要とされないので大幅に高速化されます。 また jsonb型の重要な利点はインデックスをサポートしていることです。

Because the <type>json</type> type stores an exact copy of the input text, it will preserve semantically-insignificant white space between tokens, as well as the order of keys within JSON objects. Also, if a JSON object within the value contains the same key more than once, all the key/value pairs are kept. (The processing functions consider the last value as the operative one.) By contrast, <type>jsonb</type> does not preserve white space, does not preserve the order of object keys, and does not keep duplicate object keys. If duplicate keys are specified in the input, only the last value is kept. json型は入力値のコピーを格納しているので、意味的に重要でないトークン間の空白だけでなく、JSONオブジェクト内のキーの順序も維持します。 また、JSONオブジェクト内に同じキーと値が複数含まれていてもすべてのキー/値のペアが保持されます。(この処理関数は最後の値1つを処理させるようにすれば済みます。) これとは対照的に、jsonbは空白を保持しません。オブジェクトキーの順序を保持せず、重複したオブジェクトキーを保持しません。重複キーを入力で指定された場合は、最後の値が保持されます。

In general, most applications should prefer to store JSON data as <type>jsonb</type>, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys. 一般的に、ほとんどのアプリケーションではJSONデータ型としてjsonb型のほうが望ましいでしょう。ただし、オブジェクトキーを従来のような順序であることを仮定する非常に特殊なニーズが存在するような場合は除きます。

<acronym>RFC</acronym> 7159 specifies that JSON strings should be encoded in UTF8. It is therefore not possible for the JSON types to conform rigidly to the JSON specification unless the database encoding is UTF8. Attempts to directly include characters that cannot be represented in the database encoding will fail; conversely, characters that can be represented in the database encoding but not in UTF8 will be allowed. RFC 7159は、JSON文字列はUTF8でエンコードすべきと指定しています。 従ってデータベースエンコーディングがUTF8でない限り、厳密にはJSON型がJSON仕様に準拠することはできません。 データベースのエンコーディングで表現できない文字を直接含めようとすると失敗します。逆に、UTF8で許可されずにデータベースのエンコーディングで許可される文字が許されてしまいます。

<acronym>RFC</acronym> 7159 permits JSON strings to contain Unicode escape sequences denoted by <literal>\u<replaceable>XXXX</replaceable></literal>. In the input function for the <type>json</type> type, Unicode escapes are allowed regardless of the database encoding, and are checked only for syntactic correctness (that is, that four hex digits follow <literal>\u</literal>). However, the input function for <type>jsonb</type> is stricter: it disallows Unicode escapes for characters that cannot be represented in the database encoding. The <type>jsonb</type> type also rejects <literal>\u0000</literal> (because that cannot be represented in <productname>PostgreSQL</productname>'s <type>text</type> type), and it insists that any use of Unicode surrogate pairs to designate characters outside the Unicode Basic Multilingual Plane be correct. Valid Unicode escapes are converted to the equivalent single character for storage; this includes folding surrogate pairs into a single character. RFC 7159 では、JSON文字列はUnicodeエスケープシーケンス \uXXXX を許可するように記述されています。 json型の入力関数は、データベースエンコーディング方式に関係なくUnicodeエスケープが許可されています。それは、構文上の正しさ(つまり\uに続けて16進数が4桁)だけをチェックしています。 しかし、jsonbの入力関数はより厳しくなります。 データベースエンコーディング方式で表現できない文字のUnicodeエスケープを禁止します。 jsonb型は\u0000も許可しません。(なぜならPostgreSQLtext型で表現できないためです。) また、Unicode基本多言語面以外の文字はUnicodeのサロゲートペアに直すことが要求されています。 有効なUnicodeエスケープは、同等の単一の文字に変換されて格納されます。これはサロゲートペアを単一の文字に変換する処理も含まれています。

注記

Many of the JSON processing functions described in <xref linkend="functions-json"/> will convert Unicode escapes to regular characters, and will therefore throw the same types of errors just described even if their input is of type <type>json</type> not <type>jsonb</type>. The fact that the <type>json</type> input function does not make these checks may be considered a historical artifact, although it does allow for simple storage (without processing) of JSON Unicode escapes in a database encoding that does not support the represented characters. 9.16で説明されているJSONの処理関数の多くは、Unicodeエスケープを通常の文字に変換します。 そして、それらの入力はjsonbでないjsonの場合でも記載された同じ種類のエラーになります。 json入力関数がこれらのチェックをしないことは歴史的経緯によるものと言えるかもしれませんが、そのために、表現された文字をサポートしないデータベースエンコーディングで、JSON Unicodeエスケープされた文字を単に格納(処理を必要としない場合)できてしまいます。

When converting textual JSON input into <type>jsonb</type>, the primitive types described by <acronym>RFC</acronym> 7159 are effectively mapped onto native <productname>PostgreSQL</productname> types, as shown in <xref linkend="json-type-mapping-table"/>. Therefore, there are some minor additional constraints on what constitutes valid <type>jsonb</type> data that do not apply to the <type>json</type> type, nor to JSON in the abstract, corresponding to limits on what can be represented by the underlying data type. Notably, <type>jsonb</type> will reject numbers that are outside the range of the <productname>PostgreSQL</productname> <type>numeric</type> data type, while <type>json</type> will not. Such implementation-defined restrictions are permitted by <acronym>RFC</acronym> 7159. However, in practice such problems are far more likely to occur in other implementations, as it is common to represent JSON's <type>number</type> primitive type as IEEE 754 double precision floating point (which <acronym>RFC</acronym> 7159 explicitly anticipates and allows for). When using JSON as an interchange format with such systems, the danger of losing numeric precision compared to data originally stored by <productname>PostgreSQL</productname> should be considered. 原文のJSONがjsonb型に変換されるときには、RFC 7159に記載されているプリミティブ型は表 8.23に記されているようにPostgreSQLのネイティブな型に変換されます。 そのため、jsonbデータ型には、json型になく、また理論上JSONにはないマイナーな制約があります。それは基礎となるデータ型に付随する制限によって表されます。 特にjsonb型は、PostgreSQLnumeric型の範囲外の数を拒否しますが、jsonは拒否しません。 このような処理系で定義される制限はRFC 7159で許可されています。 しかし、それは IEEE 754 倍精度浮動小数点がJSONのnumberプリミティブ型を表すのが一般的であるように、実際には他の実装でこのような問題が発生することの方がはるかに可能性が高いです(RFC 7159が明示的に予測して、許可しています)。 このようなシステムとPostgreSQLで交換フォーマットとしてJSONを使用する場合は、数値精度を失う危険性があることを把握しておく必要があります。

Conversely, as noted in the table there are some minor restrictions on the input format of JSON primitive types that do not apply to the corresponding <productname>PostgreSQL</productname> types. 逆に、表に示すようにJSONプリミティブ型の入力フォーマットには、対応するPostgreSQL型と適合しない、いくつかのマイナーな制限があります。

表8.23 JSONプリミティブ型とPostgreSQL型の対応表

<title>JSON Primitive Types and Corresponding <productname>PostgreSQL</productname> Types</title>
JSON プリミティブ型PostgreSQL注釈
stringtext\u0000は許可されません。 またそのデータベースエンコーディング方式で利用できない文字を表現するユニコードエスケープも許可されません。
numbernumericNaNinfinity 値は許可されません
booleanboolean小文字のtruefalse という綴りのみ許可されます
null(none)SQLのNULLとは概念が異なります

8.14.1. JSONの入出力構文 #

<title>JSON Input and Output Syntax</title>

The input/output syntax for the JSON data types is as specified in <acronym>RFC</acronym> 7159. JSON型の入出力構文の仕様はRFC 7159 に規定されています。

The following are all valid <type>json</type> (or <type>jsonb</type>) expressions: 以下は、すべて有効なjson型(または jsonb型)の式です。


&#45;- Simple scalar/primitive value
&#45;- Primitive values can be numbers, quoted strings, true, false, or null

-- シンプルなスカラ/プリミティブ値
-- プリミティブ値は、数値、引用符で括られた文字列、true、 false、またはnullです。
SELECT '5'::json;


&#45;- Array of zero or more elements (elements need not be of same type)

-- 0個以上の要素の配列(要素は同じ型である必要はありません)。
SELECT '[1, 2, "foo", null]'::json;


&#45;- Object containing pairs of keys and values
&#45;- Note that object keys must always be quoted strings

-- キーと値のペアを含むオブジェクト
-- オブジェクトキーは常に引用符で括られた文字列でなければならないことに注意してください。
SELECT '{"bar": "baz", "balance": 7.77, "active": false}'::json;


&#45;- Arrays and objects can be nested arbitrarily

-- 配列とオブジェクトは任意に入れ子にすることができます。
SELECT '{"foo": [true, "bar"], "tags": {"a": 1, "b": null}}'::json;

As previously stated, when a JSON value is input and then printed without any additional processing, <type>json</type> outputs the same text that was input, while <type>jsonb</type> does not preserve semantically-insignificant details such as whitespace. For example, note the differences here: 先に述べたようにJSONの値が入力されたときに、その後、追加の処理を行わずに表示する場合、jsonは入力と同じテキストが出力されます、jsonbでは、空白のような意味を持たない情報を保持しません。 例を示します。ここでは相違点に注意してください。

SELECT '{"bar": "baz", "balance": 7.77, "active":false}'::json;
                      json
-------------------------------------------------
 {"bar": "baz", "balance": 7.77, "active":false}
(1 row)

SELECT '{"bar": "baz", "balance": 7.77, "active":false}'::jsonb;
                      jsonb
--------------------------------------------------
 {"bar": "baz", "active": false, "balance": 7.77}
(1 row)

One semantically-insignificant detail worth noting is that in <type>jsonb</type>, numbers will be printed according to the behavior of the underlying <type>numeric</type> type. In practice this means that numbers entered with <literal>E</literal> notation will be printed without it, for example: もう一つ注目に値するのは、jsonbでは、数値はnumeric型の動作に応じて表示され、意味を持たない情報を保持しません。実際には数字はE表記なしで表示されることを意味します。 例を示します。

SELECT '{"reading": 1.230e-5}'::json, '{"reading": 1.230e-5}'::jsonb;
         json          |          jsonb
-----------------------+-------------------------
 {"reading": 1.230e-5} | {"reading": 0.00001230}
(1 row)

However, <type>jsonb</type> will preserve trailing fractional zeroes, as seen in this example, even though those are semantically insignificant for purposes such as equality checks. しかし、この例に見られるようにjsonbは小数の末尾のゼロを保持します。それにも関わらず、等しいかチェックする場合等では、意味的に重要ではありません。

For the list of built-in functions and operators available for constructing and processing JSON values, see <xref linkend="functions-json"/>. JSONの値の作成と処理に使用可能な組み込み関数と演算子のリストについては、9.16を参照してください。

8.14.2. JSONドキュメントの設計 #

<title>Designing JSON Documents</title>

Representing data as JSON can be considerably more flexible than the traditional relational data model, which is compelling in environments where requirements are fluid. It is quite possible for both approaches to co-exist and complement each other within the same application. However, even for applications where maximal flexibility is desired, it is still recommended that JSON documents have a somewhat fixed structure. The structure is typically unenforced (though enforcing some business rules declaratively is possible), but having a predictable structure makes it easier to write queries that usefully summarize a set of <quote>documents</quote> (datums) in a table. JSONデータは従来のリレーショナルデータモデルよりもかなり柔軟に表現することができます。そのため、要件が変わりやすい環境では説得力があります。 そして、それは同じアプリケーション内で、両方のアプローチが共存し相互に補完することが可能です。 しかし、最大の柔軟性が要求されるアプリケーションのためでもJSONドキュメントには、まだいくらかの固定構造を持つことを推奨します。 構造は(いくつかのビジネスルールを強制することは宣言的に可能であるが)、一般的に強制されないですが、テーブル内のドキュメント(データ)セットをまとめて予測可能な構造にすることで、簡単に問い合わせを記述することができます。

JSON data is subject to the same concurrency-control considerations as any other data type when stored in a table. Although storing large documents is practicable, keep in mind that any update acquires a row-level lock on the whole row. Consider limiting JSON documents to a manageable size in order to decrease lock contention among updating transactions. Ideally, JSON documents should each represent an atomic datum that business rules dictate cannot reasonably be further subdivided into smaller datums that could be modified independently. JSONデータはテーブルに格納するとき、他のデータ型と同一の同時実行制御の対象となります。大きな文章を保存することは実行可能ですが、すべての更新が行レベルロックを取得することに留意してください。 更新トランザクション間のロックの競合を減少させるために、管理可能なサイズにJSONドキュメントを制限することを検討してください。 理想的には、JSONドキュメントはビジネス・ルール上、独立して変更することができない単位までデータを分割すべきです。

8.14.3. jsonb型用包含演算子と存在演算子 #

<title><type>jsonb</type> Containment and Existence</title>

Testing <firstterm>containment</firstterm> is an important capability of <type>jsonb</type>. There is no parallel set of facilities for the <type>json</type> type. Containment tests whether one <type>jsonb</type> document has contained within it another one. These examples return true except as noted: 包含演算子による検査はjsonb型の重要な機能です。 json型には同等の機能セットはありません。 jsonbドキュメントが、その中に指定するドキュメントを含むかどうかを検査します。 これらの例は、特に記載がないかぎりtrueを返します。


&#45;- Simple scalar/primitive values contain only the identical value:

-- 単純なスカラ/プリミティブ値は、同一の値が含まれています。
SELECT '"foo"'::jsonb @> '"foo"'::jsonb;


&#45;- The array on the right side is contained within the one on the left:

-- 左辺の配列に右辺の配列が含まれています。
SELECT '[1, 2, 3]'::jsonb @> '[1, 3]'::jsonb;


&#45;- Order of array elements is not significant, so this is also true:

-- 配列要素の順序は重要ではありませんので、これもまた真になります。
SELECT '[1, 2, 3]'::jsonb @> '[3, 1]'::jsonb;


&#45;- Duplicate array elements don't matter either:

-- 配列要素に重複が含まれているかは問題ではありません。
SELECT '[1, 2, 3]'::jsonb @> '[1, 2, 2]'::jsonb;


&#45;- The object with a single pair on the right side is contained
&#45;- within the object on the left side:

-- 右辺の単一ペアを持つオブジェクトが左辺のオブジェクト内に含まれています。
SELECT '{"product": "PostgreSQL", "version": 9.4, "jsonb": true}'::jsonb @> '{"version": 9.4}'::jsonb;


&#45;- The array on the right side is <emphasis>not</emphasis> considered contained within the
&#45;- array on the left, even though a similar array is nested within it:

-- 右辺の配列は左辺の配列に含まれません、
-- 類似の配列が、その中のネストに含まれているにも関わらず。

SELECT '[1, 2, [1, 3]]'::jsonb @&gt; '[1, 3]'::jsonb;  &#45;- yields false

SELECT '[1, 2, [1, 3]]'::jsonb @> '[1, 3]'::jsonb;  -- falseになる


&#45;- But with a layer of nesting, it is contained:

-- しかし、ネストで層を合わせれば含まれるようになります。
SELECT '[1, 2, [1, 3]]'::jsonb @> '[[1, 3]]'::jsonb;


&#45;- Similarly, containment is not reported here:

-- 同様に、これも含まれません。

SELECT '{"foo": {"bar": "baz"}}'::jsonb @&gt; '{"bar": "baz"}'::jsonb;  &#45;- yields false

SELECT '{"foo": {"bar": "baz"}}'::jsonb @> '{"bar": "baz"}'::jsonb;  -- falseになる


&#45;- A top-level key and an empty object is contained:

-- トップレベルのキーと空のオブジェクトが含まれる。
SELECT '{"foo": {"bar": "baz"}}'::jsonb @> '{"foo": {}}'::jsonb;

The general principle is that the contained object must match the containing object as to structure and data contents, possibly after discarding some non-matching array elements or object key/value pairs from the containing object. But remember that the order of array elements is not significant when doing a containment match, and duplicate array elements are effectively considered only once. 一般原則では、オブジェクトにオブジェクトが含まれているかを判断するには、いくつかの条件に一致しない配列要素とキー/値のペアを含むオブジェクトを捨てた後に構造とデータを一致させる必要があります。 しかし、条件に一致するには配列要素の順序は重要ではなく、重複要素は一回のみ有効に評価されることを覚えておく必要があります。

As a special exception to the general principle that the structures must match, an array may contain a primitive value: 構造が一致しなければならないという一般原則の特別な例外として、配列はプリミティブな値を含めることができます。


&#45;- This array contains the primitive string value:

-- この配列はプリミティブな文字列を含みます。
SELECT '["foo", "bar"]'::jsonb @> '"bar"'::jsonb;


&#45;- This exception is not reciprocal &#45;- non-containment is reported here:

-- この例外は相互的ではありません。 -- これは含まれません。

SELECT '"bar"'::jsonb @&gt; '["bar"]'::jsonb;  &#45;- yields false

SELECT '"bar"'::jsonb @> '["bar"]'::jsonb;  -- falseになる

<type>jsonb</type> also has an <firstterm>existence</firstterm> operator, which is a variation on the theme of containment: it tests whether a string (given as a <type>text</type> value) appears as an object key or array element at the top level of the <type>jsonb</type> value. These examples return true except as noted: jsonb型は、また存在演算子を持ちます。包含の変種です。それは文字列(与えられたtext値)が、jsonb値のオブジェクトキーまたは配列のトップレベルに存在するかどうかを検査します。 これらの例は、特に記載がないかぎりtrueを返します。


&#45;- String exists as array element:

-- 文字列が配列要素に存在する。
SELECT '["foo", "bar", "baz"]'::jsonb ? 'bar';


&#45;- String exists as object key:

-- 文字列がオブジェクトキーに存在する。
SELECT '{"foo": "bar"}'::jsonb ? 'foo';


&#45;- Object values are not considered:

-- オブジェクト値は考慮されません。

SELECT '{"foo": "bar"}'::jsonb ? 'bar';  &#45;- yields false

SELECT '{"foo": "bar"}'::jsonb ? 'bar';  -- falseになる


&#45;- As with containment, existence must match at the top level:

-- オブジェクトはトップレベルから一致するように存在する必要があります。

SELECT '{"foo": {"bar": "baz"}}'::jsonb ? 'bar'; &#45;- yields false

SELECT '{"foo": {"bar": "baz"}}'::jsonb ? 'bar'; -- falseになる


&#45;- A string is considered to exist if it matches a primitive JSON string:

-- 文字列はJSONプリミティブ文字列と一致させることができます。
SELECT '"foo"'::jsonb ? 'foo';

JSON objects are better suited than arrays for testing containment or existence when there are many keys or elements involved, because unlike arrays they are internally optimized for searching, and do not need to be searched linearly. JSONオブジェクトは、関係するキーや要素が多く存在する場合、含むかどうかまたは存在するかどうかのテストに適しています。なぜなら配列とは異なり、リニア検索をする必要がなく、内部的に検索に最適化されています。

ヒント

Because JSON containment is nested, an appropriate query can skip explicit selection of sub-objects. As an example, suppose that we have a <structfield>doc</structfield> column containing objects at the top level, with most objects containing <literal>tags</literal> fields that contain arrays of sub-objects. This query finds entries in which sub-objects containing both <literal>"term":"paris"</literal> and <literal>"term":"food"</literal> appear, while ignoring any such keys outside the <literal>tags</literal> array: JSONでは包含がネストされるので、適切な問い合わせではサブオブジェクトの明示的な選択を省略することが出来ます。 例を挙げます。 doc列にトップレベルのオブジェクトがあります。 このオブジェクトには、tagsフィールドが含まれ、このフィールドにサブオブジェクトの配列が多く含まれているとします。 以下の問い合わせは、サブオブジェクトが"term":"paris""term":"food"の両方を含むエントリを探します。 そのときtags配列の外側にある、それらのキーは無視されます。

SELECT doc->'site_name' FROM websites
  WHERE doc @> '{"tags":[{"term":"paris"}, {"term":"food"}]}';

One could accomplish the same thing with, say, 同じことを達成することは出来ます。例えば、

SELECT doc->'site_name' FROM websites
  WHERE doc->'tags' @> '[{"term":"paris"}, {"term":"food"}]';

but that approach is less flexible, and often less efficient as well. しかし、そのアプローチは柔軟性に欠け、効率も落ちます。

On the other hand, the JSON existence operator is not nested: it will only look for the specified key or array element at top level of the JSON value. 一方、JSONの存在演算子は、ネストしていません。 JSONの値の最上位に指定されたキーまたは配列要素のみを探します。

The various containment and existence operators, along with all other JSON operators and functions are documented in <xref linkend="functions-json"/>. JSONの様々な包含演算子や存在演算子、他のすべてのJSON演算子と関数は 9.16に記載されています。

8.14.4. jsonb インデックス #

<title><type>jsonb</type> Indexing</title>

GIN indexes can be used to efficiently search for keys or key/value pairs occurring within a large number of <type>jsonb</type> documents (datums). Two GIN <quote>operator classes</quote> are provided, offering different performance and flexibility trade-offs. GINインデックスは、多数のjsonbドキュメント(データ)のキーやキー/値ペアを効率的に検索するときに用いることができます。 異なるパフォーマンスと柔軟性のトレードオフを持つ、2つのGIN 演算子クラス が提供されています。

The default GIN operator class for <type>jsonb</type> supports queries with the key-exists operators <literal>?</literal>, <literal>?|</literal> and <literal>?&amp;</literal>, the containment operator <literal>@&gt;</literal>, and the <type>jsonpath</type> match operators <literal>@?</literal> and <literal>@@</literal>. (For details of the semantics that these operators implement, see <xref linkend="functions-jsonb-op-table"/>.) An example of creating an index with this operator class is: jsonb型の問い合わせでサポートしているデフォルトのGIN演算子クラスは、キーが存在するかの演算子として??|?&があり、包含演算子として@>があり、jsonpathマッチング演算子として@?@@があります。 (これらの演算子の意味の詳細は、表 9.46を参照してください。) この演算子クラスのインデックスを作成する例。

CREATE INDEX idxgin ON api USING GIN (jdoc);

The non-default GIN operator class <literal>jsonb_path_ops</literal> does not support the key-exists operators, but it does support <literal>@&gt;</literal>, <literal>@?</literal> and <literal>@@</literal>. An example of creating an index with this operator class is: デフォルトでないGIN演算子クラスjsonb_path_opsは、キーが存在するかの演算子をサポートしませんが、@>@?@@をサポートします。 この演算子クラスのインデックスを作成する例。

CREATE INDEX idxginp ON api USING GIN (jdoc jsonb_path_ops);

Consider the example of a table that stores JSON documents retrieved from a third-party web service, with a documented schema definition. A typical document is: サードパーティのWebサービスから、ドキュメント化されたスキーマ定義を持つJSONドキュメントを取得し、格納するテーブルの例を考えてみましょう。 典型的なドキュメントは、次のとおりです。

{
    "guid": "9c36adc1-7fb5-4d5b-83b4-90356a46061a",
    "name": "Angela Barton",
    "is_active": true,
    "company": "Magnafone",
    "address": "178 Howard Place, Gulf, Washington, 702",
    "registered": "2009-11-07T08:53:22 +08:00",
    "latitude": 19.793713,
    "longitude": 86.513373,
    "tags": [
        "enim",
        "aliquip",
        "qui"
    ]
}

We store these documents in a table named <structname>api</structname>, in a <type>jsonb</type> column named <structfield>jdoc</structfield>. If a GIN index is created on this column, queries like the following can make use of the index: テーブル名 apijsonb型でjdocをカラム名として格納します。 このカラムにGINインデックスを作成した場合、以下のような問い合わせがインデックスを利用することができます。


&#45;- Find documents in which the key "company" has value "Magnafone"

-- "company"キー が "Magnafone"値であるものを見つける
SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @> '{"company": "Magnafone"}';

However, the index could not be used for queries like the following, because though the operator <literal>?</literal> is indexable, it is not applied directly to the indexed column <structfield>jdoc</structfield>: しかし 次のような問い合わせはインデックスを使用しません。なぜなら、?演算子はインデックス可能ですが、jdocカラムのインデックスが直接適用されていないためです。


&#45;- Find documents in which the key "tags" contains key or array element "qui"

-- キー "tags" の配列要素に "qui"が含まれているか見つける
SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc -> 'tags' ? 'qui';

Still, with appropriate use of expression indexes, the above query can use an index. If querying for particular items within the <literal>"tags"</literal> key is common, defining an index like this may be worthwhile: それでも、上記の問い合わせは、式インデックスを適切に使用することでインデックスを使用することができます。一般的な "tags"キーから特定の項目を照会する場合、このようなインデックスを定義すると良いかもしれません。

CREATE INDEX idxgintags ON api USING GIN ((jdoc -> 'tags'));

Now, the <literal>WHERE</literal> clause <literal>jdoc -&gt; 'tags' ? 'qui'</literal> will be recognized as an application of the indexable operator <literal>?</literal> to the indexed expression <literal>jdoc -&gt; 'tags'</literal>. (More information on expression indexes can be found in <xref linkend="indexes-expressional"/>.) さて、 WHERE句の jdoc -> 'tags' ? 'qui'は、インデックス式jdoc->'tags'では、?演算子はインデックス可能として認識されます。 (式インデックスに関する詳細情報は11.7を参照してください。)

Another approach to querying is to exploit containment, for example: 別のアプローチとして包含を利用する問い合わせがあります。例を示します。


&#45;- Find documents in which the key "tags" contains array element "qui"

-- キー "tags"に 要素"qui"が含まれるかどうか見つける
SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @> '{"tags": ["qui"]}';

A simple GIN index on the <structfield>jdoc</structfield> column can support this query. But note that such an index will store copies of every key and value in the <structfield>jdoc</structfield> column, whereas the expression index of the previous example stores only data found under the <literal>tags</literal> key. While the simple-index approach is far more flexible (since it supports queries about any key), targeted expression indexes are likely to be smaller and faster to search than a simple index. jdocカラムのシンプルなGINインデックスは、この問い合わせをサポートすることができます。 しかし、前の例では、tagsキーの下にあるデータのみをインデックスに格納していたのに対して、そのようなインデックスは、jdocのすべてのキーと値のコピーを保存しますので、注意が必要です。 シンプルなインデックスアプローチは(それが全てのキーについての問い合わせをサポートしているため)はるかに柔軟ですが、ターゲット式インデックスは単純なインデックスより小さく、検索のときに高速である可能性が高くなります。

GIN indexes also support the <literal>@?</literal> and <literal>@@</literal> operators, which perform <type>jsonpath</type> matching. Examples are GINインデックスはjsonpathのマッチングを実行する@?演算子と@@演算子もサポートします。 例は以下の通りです。

SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @? '$.tags[*] ? (@ == "qui")';

SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @@ '$.tags[*] == "qui"';

For these operators, a GIN index extracts clauses of the form <literal><replaceable>accessors_chain</replaceable> = <replaceable>constant</replaceable></literal> out of the <type>jsonpath</type> pattern, and does the index search based on the keys and values mentioned in these clauses. The accessors chain may include <literal>.<replaceable>key</replaceable></literal>, <literal>[*]</literal>, and <literal>[<replaceable>index</replaceable>]</literal> accessors. The <literal>jsonb_ops</literal> operator class also supports <literal>.*</literal> and <literal>.**</literal> accessors, but the <literal>jsonb_path_ops</literal> operator class does not. これらの演算子に対して、GINインデックスは、jsonpathパターンからaccessors_chain = constantの形式の句を抽出し、句内で使われているキーと値に基づいてインデックスサーチをします。 アクセサチェーン(accessors chain)は.key[*][index]アクセサを含みます。 jsonb_ops演算子クラスは.*.**アクセサもサポートしますが、jsonb_path_ops演算子クラスはサポートしません。

Although the <literal>jsonb_path_ops</literal> operator class supports only queries with the <literal>@&gt;</literal>, <literal>@?</literal> and <literal>@@</literal> operators, it has notable performance advantages over the default operator class <literal>jsonb_ops</literal>. A <literal>jsonb_path_ops</literal> index is usually much smaller than a <literal>jsonb_ops</literal> index over the same data, and the specificity of searches is better, particularly when queries contain keys that appear frequently in the data. Therefore search operations typically perform better than with the default operator class. jsonb_path_ops演算子クラスは、@>@?@@演算子をサポートしているだけですが、デフォルト演算子クラスのjsonb_opsよりも顕著なパフォーマンス上の利点があります。 jsonb_path_opsインデックスは、通常同じデータのjsonb_opsインデックスよりもはるかに小さく、データの中で頻繁に現れるキーを含む場合のような特別な検索には、より良くなります。 そのため、デフォルトの演算子クラスよりも検索性能が良くなります。

The technical difference between a <literal>jsonb_ops</literal> and a <literal>jsonb_path_ops</literal> GIN index is that the former creates independent index items for each key and value in the data, while the latter creates index items only for each value in the data. jsonb_opsjsonb_path_opsのGINインデックスの技術的差異は、前者はデータのキーと値のための独立したインデックスを作成しますが、後者は、データの値に対してのみインデックスを作成します。 [7] Basically, each <literal>jsonb_path_ops</literal> index item is a hash of the value and the key(s) leading to it; for example to index <literal>{"foo": {"bar": "baz"}}</literal>, a single index item would be created incorporating all three of <literal>foo</literal>, <literal>bar</literal>, and <literal>baz</literal> into the hash value. Thus a containment query looking for this structure would result in an extremely specific index search; but there is no way at all to find out whether <literal>foo</literal> appears as a key. On the other hand, a <literal>jsonb_ops</literal> index would create three index items representing <literal>foo</literal>, <literal>bar</literal>, and <literal>baz</literal> separately; then to do the containment query, it would look for rows containing all three of these items. While GIN indexes can perform such an AND search fairly efficiently, it will still be less specific and slower than the equivalent <literal>jsonb_path_ops</literal> search, especially if there are a very large number of rows containing any single one of the three index items. 基本的に、jsonb_path_opsインデックス項目は、値とキーのハッシュです。例えば、{"foo": {"bar": "baz"}}のインデックスはハッシュ値にfoobarbazすべてを組み込んで作成されます。 したがって、包含問い合わせのためのインデックス検索は、非常に特定の構造を返すようになっています。 しかしfooがキーとして表示されるかどうかを調べるには全く方法はありません。 一方、jsonb_opsインデックスは個別にはfoobarbazを表す3つのインデックス項目を作成します。 その後、包含問い合わせをおこなうには、これらの項目の3つすべてを含む行を探します。 GINインデックスは、かなり効率的に検索することができますが、特に3つの索引項目のいずれかで、非常に多数の行が単一の場合に、同等のjsonb_path_ops検索よりも遅くなります。

A disadvantage of the <literal>jsonb_path_ops</literal> approach is that it produces no index entries for JSON structures not containing any values, such as <literal>{"a": {}}</literal>. If a search for documents containing such a structure is requested, it will require a full-index scan, which is quite slow. <literal>jsonb_path_ops</literal> is therefore ill-suited for applications that often perform such searches. jsonb_path_opsアプローチの欠点は、{"a": {}}のような、任意の値を含まないJSON構造のためのインデックスエントリを生成しません。 このような構造を含むドキュメントの検索が要求された場合、それは、フルインデックススキャンを必要とします。それは非常に遅くなります。そのため、 jsonb_path_opsは、多くの場合、そのような検索を実行するのには不適当です。

<type>jsonb</type> also supports <literal>btree</literal> and <literal>hash</literal> indexes. These are usually useful only if it's important to check equality of complete JSON documents. The <literal>btree</literal> ordering for <type>jsonb</type> datums is seldom of great interest, but for completeness it is: jsonb型は、btreehash インデックスもサポートします。 これらは通常、JSONドキュメントの完全性をチェックすることが重要な場合のみ有用です。 jsonbのためのbtree順序には、興味深いことはほとんどありませんが、しかし、完全さのために次に示します。

Object > Array > Boolean > Number > String > Null

Object with n pairs > object with n - 1 pairs

Array with n elements > array with n - 1 elements

Objects with equal numbers of pairs are compared in the order: ペアの同じ番号を持つオブジェクトは、順に比較されます。

key-1, value-1, key-2 ...

Note that object keys are compared in their storage order; in particular, since shorter keys are stored before longer keys, this can lead to results that might be unintuitive, such as: そのオブジェクトのキーは、その格納順に比較されることに注意してください。 短いキーは長いキーの前に格納されているため、特にこれは、次のような直感的でない結果に結果につながるかもしれません。

{ "aa": 1, "c": 1} > {"b": 1, "d": 1}

Similarly, arrays with equal numbers of elements are compared in the order: 同様に、配列と同じ番号を持つ要素を比較する順番。

element-1, element-2 ...

Primitive JSON values are compared using the same comparison rules as for the underlying <productname>PostgreSQL</productname> data type. Strings are compared using the default database collation. JSONプリミティブ値は基本的にPostgreSQLデータ型と同じルールで比較されます。文字列は、デフォルトのデータベース照合を使用して比較されます

8.14.5. jsonbの添字 #

<title><type>jsonb</type> Subscripting</title>

The <type>jsonb</type> data type supports array-style subscripting expressions to extract and modify elements. Nested values can be indicated by chaining subscripting expressions, following the same rules as the <literal>path</literal> argument in the <literal>jsonb_set</literal> function. If a <type>jsonb</type> value is an array, numeric subscripts start at zero, and negative integers count backwards from the last element of the array. Slice expressions are not supported. The result of a subscripting expression is always of the jsonb data type. jsonbデータ型は要素を取り出したり修正したりするために配列形式の添字表現をサポートします。 入れ子になった値は、jsonb_set関数でのpath引数と同じ規則に従って、添字表現をつなげることで指定できます。 jsonb値が配列であれば、数字の添字はゼロから始まり、負の整数は配列の最後の要素から逆に数えます。 スライス表現はサポートされていません。 添字表現の結果は、必ずjsonbデータ型です。

<command>UPDATE</command> statements may use subscripting in the <literal>SET</literal> clause to modify <type>jsonb</type> values. Subscript paths must be traversable for all affected values insofar as they exist. For instance, the path <literal>val['a']['b']['c']</literal> can be traversed all the way to <literal>c</literal> if every <literal>val</literal>, <literal>val['a']</literal>, and <literal>val['a']['b']</literal> is an object. If any <literal>val['a']</literal> or <literal>val['a']['b']</literal> is not defined, it will be created as an empty object and filled as necessary. However, if any <literal>val</literal> itself or one of the intermediary values is defined as a non-object such as a string, number, or <literal>jsonb</literal> <literal>null</literal>, traversal cannot proceed so an error is raised and the transaction aborted. UPDATE文では、jsonb値を修正するSET句内で添字が使えます。 添字のパスは、存在する範囲では影響する値すべてが到達可能でなければなりません。 例えば、パスval['a']['b']['c']は、valval['a']val['a']['b']それぞれがオブジェクトであれば、cまでたどることができます。 val['a']またはval['a']['b']が定義されていなければ、空のオブジェクトとして作られ必要に応じて埋められます。 しかしながら、val自身または途中の値の1つでも、文字列、数値、jsonb nullのような非オブジェクトとして定義されていれば、到達できないためエラーが発生し、トランザクションはアボートされます。

An example of subscripting syntax: 添字構文の例です。



&#45;- Extract object value by key

-- キーでオブジェクトの値を取り出す
SELECT ('{"a": 1}'::jsonb)['a'];


&#45;- Extract nested object value by key path

-- キーのパスで入れ子のオブジェクトの値を取り出す
SELECT ('{"a": {"b": {"c": 1}}}'::jsonb)['a']['b']['c'];


&#45;- Extract array element by index

-- インデックスで配列要素を取り出す
SELECT ('[1, "2", null]'::jsonb)[1];


&#45;- Update object value by key. Note the quotes around '1': the assigned
&#45;- value must be of the jsonb type as well

-- キーでオブジェクトの値を更新する。'1'の周りの一重引用符に注意。
-- 代入する値もjsonb型でなければならない
UPDATE table_name SET jsonb_field['key'] = '1';


&#45;- This will raise an error if any record's jsonb_field['a']['b'] is something
&#45;- other than an object. For example, the value {"a": 1} has a numeric value
&#45;- of the key 'a'.

-- これはjsonb_field['a']['b']のいずれかのデータがオブジェクト以外のものであればエラーになる。
-- 例えば、値{"a": 1}はキー'a'の数値を持つ。
UPDATE table_name SET jsonb_field['a']['b']['c'] = '1';


&#45;- Filter records using a WHERE clause with subscripting. Since the result of
&#45;- subscripting is jsonb, the value we compare it against must also be jsonb.
&#45;- The double quotes make "value" also a valid jsonb string.

-- WHERE句で添字を使ってデータにフィルタを掛ける。
-- 添字による結果はjsonbなので、それと比較する値もjsonbでなければならない。
-- 二重引用符により"value"も有効なjsonb文字列になる。
SELECT * FROM table_name WHERE jsonb_field['key'] = '"value"';

<type>jsonb</type> assignment via subscripting handles a few edge cases differently from <literal>jsonb_set</literal>. When a source <type>jsonb</type> value is <literal>NULL</literal>, assignment via subscripting will proceed as if it was an empty JSON value of the type (object or array) implied by the subscript key: 添字によるjsonbの代入は、まれにjsonb_setとは異なる場合があります。 元のjsonb値がNULLの場合、添字による代入は、添字のキーで暗示されるその型の空のJSON値(オブジェクトまたは配列)であるかのように処理されます。


&#45;- Where jsonb_field was NULL, it is now {"a": 1}

-- jsonb_fieldがNULLの場合、{"a": 1}になる
UPDATE table_name SET jsonb_field['a'] = '1';


&#45;- Where jsonb_field was NULL, it is now [1]

-- jsonb_fieldがNULLの場合、[1]になる
UPDATE table_name SET jsonb_field[0] = '1';

If an index is specified for an array containing too few elements, <literal>NULL</literal> elements will be appended until the index is reachable and the value can be set. 要素が足りない配列に対してインデックスを指定した場合、インデックスが到達可能になって値が設定できるようになるまでNULL要素が追加されます。


&#45;- Where jsonb_field was [], it is now [null, null, 2];
&#45;- where jsonb_field was [0], it is now [0, null, 2]

-- jsonb_fieldが[]なら、[null, null, 2]になり、
-- jsonb_fieldが[0]なら、[0, null, 2]になる
UPDATE table_name SET jsonb_field[2] = '2';

A <type>jsonb</type> value will accept assignments to nonexistent subscript paths as long as the last existing element to be traversed is an object or array, as implied by the corresponding subscript (the element indicated by the last subscript in the path is not traversed and may be anything). Nested array and object structures will be created, and in the former case <literal>null</literal>-padded, as specified by the subscript path until the assigned value can be placed. 対応する添字が暗示するように、到達できる最後の存在する要素がオブジェクトか配列である限り、jsonb値は存在しない添字のパスへの代入を受け付けます。 (パスの最後の添字で指定される要素には到達しませんし、何でも構いません。) 入れ子の配列やオブジェクト構造が作られ、前者の場合には、添字のパスにより指定されたように値が代入できるようになるまでnullで埋められます。


&#45;- Where jsonb_field was {}, it is now {"a": [{"b": 1}]}

-- jsonb_fieldが{}であれば、{"a": [{"b": 1}]}になる
UPDATE table_name SET jsonb_field['a'][0]['b'] = '1';


&#45;- Where jsonb_field was [], it is now [null, {"a": 1}]

-- jsonb_fieldが[]であれば、[null, {"a": 1}]になる
UPDATE table_name SET jsonb_field[1]['a'] = '1';

8.14.6. 変換 #

<title>Transforms</title>

Additional extensions are available that implement transforms for the <type>jsonb</type> type for different procedural languages. 異なるプロシージャ言語でjsonb型の変換を実装した追加の拡張が入手可能です。

The extensions for PL/Perl are called <literal>jsonb_plperl</literal> and <literal>jsonb_plperlu</literal>. If you use them, <type>jsonb</type> values are mapped to Perl arrays, hashes, and scalars, as appropriate. PL/Perl向けの拡張は、jsonb_plperljsonb_plperluと呼ばれます。 この拡張を使うとjsonbの値はPerlの配列、ハッシュ、スカラの適切なものにマップされます。

The extension for PL/Python is called <literal>jsonb_plpython3u</literal>. If you use it, <type>jsonb</type> values are mapped to Python dictionaries, lists, and scalars, as appropriate. PL/Python向けの拡張は、jsonb_plpython3uと呼ばれます。 この拡張を使うと、jsonbの値はPythonの辞書型、リスト、スカラの適切なものにマップされます。

Of these extensions, <literal>jsonb_plperl</literal> is considered <quote>trusted</quote>, that is, it can be installed by non-superusers who have <literal>CREATE</literal> privilege on the current database. The rest require superuser privilege to install. 上記の拡張のうち、jsonb_plperltrustedと見なされます。つまり、現在のデータベースに対してCREATE権限を持つ非スーパーユーザがインストールできます。 残りはインストールするのにスーパーユーザ権限が必要です。

8.14.7. jsonpath型 #

<title>jsonpath Type</title>

The <type>jsonpath</type> type implements support for the SQL/JSON path language in <productname>PostgreSQL</productname> to efficiently query JSON data. It provides a binary representation of the parsed SQL/JSON path expression that specifies the items to be retrieved by the path engine from the JSON data for further processing with the SQL/JSON query functions. jsonpath型は、PostgreSQLでJSONデータの効率的な問い合わせをするために、SQL/JSONパス言語のサポートを実装しています。 構文解析されたSQL/JSONパス式のバイナリ表現を提供し、SQL/JSON問い合わせ関数でさらに処理するために、パスエンジンがJSONデータから取得する項目を指定します。

The semantics of SQL/JSON path predicates and operators generally follow SQL. At the same time, to provide a natural way of working with JSON data, SQL/JSON path syntax uses some JavaScript conventions: SQL/JSONパス述部および演算子のセマンティクスは、SQLに準拠しています。 同時に、JSONデータを処理する自然な方法を提供するために、SQL/JSONのパス構文ではいくつかのJavaScript規則を使用します。

  • Dot (<literal>.</literal>) is used for member access. ドット(.)は、メンバアクセスに使用されます。

  • Square brackets (<literal>[]</literal>) are used for array access. 大括弧([])は配列アクセスに使用されます。

  • SQL/JSON arrays are 0-relative, unlike regular SQL arrays that start from 1. 1から始まる通常のSQL配列とは異なり、SQL/JSON配列は0スタートです。

Numeric literals in SQL/JSON path expressions follow JavaScript rules, which are different from both SQL and JSON in some minor details. For example, SQL/JSON path allows <literal>.1</literal> and <literal>1.</literal>, which are invalid in JSON. Non-decimal integer literals and underscore separators are supported, for example, <literal>1_000_000</literal>, <literal>0x1EEE_FFFF</literal>, <literal>0o273</literal>, <literal>0b100101</literal>. In SQL/JSON path (and in JavaScript, but not in SQL proper), there must not be an underscore separator directly after the radix prefix. SQL/JSONパス式の数値リテラルは、JavaScriptルールに従います。JavaScriptルールは、いくつかの細かい点でSQLやJSONのいずれとも異なります。 例えば、SQL/JSONパスでは.11.が有効ですが、JSONでは無効です。 例えば、1_000_0000x1EEE_FFFF0o2730b100101など、10進数でない整数リテラルやアンダースコアの区切り文字がサポートされています。 SQL/JSONパス式では(およびJavaScriptでは、しかし本来のSQLではそうではありません)、基数の接頭辞の直後にアンダースコアの区切り文字を使用できません。

An SQL/JSON path expression is typically written in an SQL query as an SQL character string literal, so it must be enclosed in single quotes, and any single quotes desired within the value must be doubled (see <xref linkend="sql-syntax-strings"/>). Some forms of path expressions require string literals within them. These embedded string literals follow JavaScript/ECMAScript conventions: they must be surrounded by double quotes, and backslash escapes may be used within them to represent otherwise-hard-to-type characters. In particular, the way to write a double quote within an embedded string literal is <literal>\"</literal>, and to write a backslash itself, you must write <literal>\\</literal>. Other special backslash sequences include those recognized in JSON strings: <literal>\b</literal>, <literal>\f</literal>, <literal>\n</literal>, <literal>\r</literal>, <literal>\t</literal>, <literal>\v</literal> for various ASCII control characters, and <literal>\u<replaceable>NNNN</replaceable></literal> for a Unicode character identified by its 4-hex-digit code point. The backslash syntax also includes two cases not allowed by JSON: <literal>\x<replaceable>NN</replaceable></literal> for a character code written with only two hex digits, and <literal>\u{<replaceable>N...</replaceable>}</literal> for a character code written with 1 to 6 hex digits. SQL/JSONパス式は通常、SQL問い合わせでSQL文字列リテラルとして記述されるため、一重引用符で囲む必要があり、値内で必要な一重引用符は二重にする必要があります (4.1.2.1を参照)。 一部の形式のパス式では、文字列リテラルを含める必要があります。 これらの埋め込み文字列リテラルは二重引用符で囲む必要があり、バックスラッシュエスケープを使用してハード・タイプ文字を表すことができます。 特に、埋め込み文字列リテラル内で二重引用符を記述する方法は\"であり、バックスラッシュを記述する必要がある場合は\\と書く必要があります。 その他の特別なバックスラッシュ構文には、以下のJSON文字列で認識されるものが含まれます。 さまざまなASCII制御用文字の\b\f\n\r\t\v、および4つの16進数のコードポイントで識別されるUnicode文字用の\uNNNNです。 バックスラッシュ構文には、JSONでは許されない2つのケースも含まれています。 \xNNは2桁の16進数だけで記述された文字コードの場合で、\u{N...}は、1~6桁の16進数で記述された文字コードの場合です。

A path expression consists of a sequence of path elements, which can be any of the following: パスの式は、次のようなパス要素のシーケンスで構成されます。

  • Path literals of JSON primitive types: Unicode text, numeric, true, false, or null. JSONプリミティブ型のパスリテラル。 ユニコードテキスト、数値、true、false、又はnullです。

  • Path variables listed in <xref linkend="type-jsonpath-variables"/>. パス変数表 8.24

  • Accessor operators listed in <xref linkend="type-jsonpath-accessors"/>. アクセサ演算子表 8.25

  • <type>jsonpath</type> operators and methods listed in <xref linkend="functions-sqljson-path-operators"/>. jsonpath演算子とメソッド9.16.2.2

  • Parentheses, which can be used to provide filter expressions or define the order of path evaluation. 括弧。フィルタ式を提供したり、パス評価の順序を定義するために使用できます。

For details on using <type>jsonpath</type> expressions with SQL/JSON query functions, see <xref linkend="functions-sqljson-path"/>. jsonpath式を使用したSQL/JSON問い合わせ関数の詳細は、9.16.2を参照してください。

表8.24 jsonpath変数

<title><type>jsonpath</type> Variables</title>
変数説明
$ 問い合わせ対象(context item)のJSON値を表す変数。
$varname A named variable. Its value can be set by the parameter <parameter>vars</parameter> of several JSON processing functions; see <xref linkend="functions-json-processing-table"/> for details. 名前付き変数。 その値はいくつかのJSON処理関数のパラメーターvarsで設定できます。 詳細は表 9.49を参照してください。 TODO: describe PASSING clause once implemented !
@フィルター式のパス評価の結果を表す変数。

表8.25 jsonpath Accessors

アクセサ演算子説明

.key

."$varname"

Member accessor that returns an object member with the specified key. If the key name matches some named variable starting with <literal>$</literal> or does not meet the JavaScript rules for an identifier, it must be enclosed in double quotes to make it a string literal. 指定されたキーを持つオブジェクトメンバを返すメンバアクセサ。 キー名が$で始まる名前付き変数に一致する場合、または識別子のJavaScriptルールを満たさない場合は、文字列リテラルとするため二重引用符で囲む必要があります。

.*

Wildcard member accessor that returns the values of all members located at the top level of the current object. 現在のオブジェクトの最上位レベルになるすべてのメンバの値を返すワイルドカードメンバアクセサ。

.**

Recursive wildcard member accessor that processes all levels of the JSON hierarchy of the current object and returns all the member values, regardless of their nesting level. This is a <productname>PostgreSQL</productname> extension of the SQL/JSON standard. 現在のオブジェクトのJSON階層のすべてのレベルを処理し、ネストされたレベルに関わらず全てのメンバ値を返す再帰的なワイルドカードメンバアクセサ。 これはSQL/JSON標準のPostgreSQLの拡張です。

.**{level}

.**{start_level to end_level}

Like <literal>.**</literal>, but selects only the specified levels of the JSON hierarchy. Nesting levels are specified as integers. Level zero corresponds to the current object. To access the lowest nesting level, you can use the <literal>last</literal> keyword. This is a <productname>PostgreSQL</productname> extension of the SQL/JSON standard. .**と似ていますが、JSON階層の指定したレベルだけを選びます。 ネストレベルは整数で指定します。 レベル0は現在のオブジェクトに対応します。 最下位のネストレベルにアクセスするのに、lastキーワードが使用できます。 これはSQL/JSON標準のPostgreSQLの拡張です。

[subscript, ...]

Array element accessor. <literal><replaceable>subscript</replaceable></literal> can be given in two forms: <literal><replaceable>index</replaceable></literal> or <literal><replaceable>start_index</replaceable> to <replaceable>end_index</replaceable></literal>. The first form returns a single array element by its index. The second form returns an array slice by the range of indexes, including the elements that correspond to the provided <replaceable>start_index</replaceable> and <replaceable>end_index</replaceable>. 配列要素アクセサ。 subscriptは、indexまたはstart_indexからend_indexまでの2つの形式で指定できます。 最初の形式は、インデックスによって単一の配列要素を返します。 2番目の形式は、指定されたstart_indexend_indexに対応する要素を含む、インデックスの範囲による配列スライスを返します。

The specified <replaceable>index</replaceable> can be an integer, as well as an expression returning a single numeric value, which is automatically cast to integer. Index zero corresponds to the first array element. You can also use the <literal>last</literal> keyword to denote the last array element, which is useful for handling arrays of unknown length. 指定されたindexには、整数だけでなく、自動的に整数にキャストされる単一の数値を返す式を指定できます。 インデックス0は最初の配列要素に対応します。 また、lastキーワードを使用して最後の配列要素を指定することもできます。 これは、長さが不明な配列の処理に役立ちます。

[*]

Wildcard array element accessor that returns all array elements. 全ての配列の要素を返すワイルドカード配列要素アクセサ。




[7] For this purpose, the term <quote>value</quote> includes array elements, though JSON terminology sometimes considers array elements distinct from values within objects. この目的のために、 という用語は配列の要素を含みますが、JSONの専門用語では、オブジェクト内の値と配列の要素が時々違うことがあります。