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

F.18. hstore — hstoreキー/値データ型 #

<title>hstore &mdash; hstore key/value datatype</title>

This module implements the <type>hstore</type> data type for storing sets of key/value pairs within a single <productname>PostgreSQL</productname> value. This can be useful in various scenarios, such as rows with many attributes that are rarely examined, or semi-structured data. Keys and values are simply text strings. 本モジュールはキー、値の組み合わせの集合を単一のPostgreSQL値に格納するためのhstoreデータ型を実装します。 あまり厳密に検査されない属性を多く持つ行や半構造化データなど、多くの状況で有用になる可能性があります。 キーと値は単純なテキスト文字列です。

This module is considered <quote>trusted</quote>, that is, it can be installed by non-superusers who have <literal>CREATE</literal> privilege on the current database. このモジュールはtrustedと見なされます。つまり、現在のデータベースに対してCREATE権限を持つ非スーパーユーザがインストールできます。

F.18.1. hstoreの外部表現 #

<title><type>hstore</type> External Representation</title>

The text representation of an <type>hstore</type>, used for input and output, includes zero or more <replaceable>key</replaceable> <literal>=&gt;</literal> <replaceable>value</replaceable> pairs separated by commas. Some examples: 入力および出力で使用されるhstore値のテキスト表現はカンマで区切られた、ゼロ以上のkey => valueという組み合わせを含みます。 以下に例を示します。

k => v
foo => bar, baz => whatever
"1-a" => "anything at all"

The order of the pairs is not significant (and may not be reproduced on output). Whitespace between pairs or around the <literal>=&gt;</literal> sign is ignored. Double-quote keys and values that include whitespace, commas, <literal>=</literal>s or <literal>&gt;</literal>s. To include a double quote or a backslash in a key or value, escape it with a backslash. 組み合わせの順序は重要ではありません(出力時に再現されないこともあります)。 組み合わせ間や=>記号の前後の空白文字は無視されます。 キーや値が空白文字、カンマ、=>を含む場合は二重引用符でくくります。 キーや値に二重引用符やバックスラッシュを含めるには、バックスラッシュでエスケープしてください。

Each key in an <type>hstore</type> is unique. If you declare an <type>hstore</type> with duplicate keys, only one will be stored in the <type>hstore</type> and there is no guarantee as to which will be kept: hstore内の各キーは一意です。 重複するキーを持つhstoreを宣言すると、hstoreには1つしか保存されません。 またどちらが残るかは保証されません。

SELECT 'a=>1,a=>2'::hstore;
  hstore
----------
 "a"=>"1"

A value (but not a key) can be an SQL <literal>NULL</literal>. For example: 値はSQLのNULLを取ることができます(キーは不可)。 以下に例を示します。

key => NULL

The <literal>NULL</literal> keyword is case-insensitive. Double-quote the <literal>NULL</literal> to treat it as the ordinary string <quote>NULL</quote>. NULLキーワードは大文字小文字の区別をしません。 nullを普通の文字列NULLとして扱うためには二重引用符でくくってください。

注記

Keep in mind that the <type>hstore</type> text format, when used for input, applies <emphasis>before</emphasis> any required quoting or escaping. If you are passing an <type>hstore</type> literal via a parameter, then no additional processing is needed. But if you're passing it as a quoted literal constant, then any single-quote characters and (depending on the setting of the <varname>standard_conforming_strings</varname> configuration parameter) backslash characters need to be escaped correctly. See <xref linkend="sql-syntax-strings"/> for more on the handling of string constants. 入力として使用される場合hstoreテキスト書式は、前もって必要な引用符付けやエスケープ処理を適用することに注意してください。 パラメータとしてhstoreリテラルを渡す場合、追加処理は必要ありません。 しかし、引用符付けしたリテラル定数として渡す場合には、単一引用符および(standard_conforming_strings設定パラメータに依存しますが)バックスラッシュ文字をすべて正しくエスケープしなければなりません。 文字列定数の取り扱いについては4.1.2.1を参照してください。

On output, double quotes always surround keys and values, even when it's not strictly necessary. 出力の場合、厳密に必要がない場合であっても、常にキーと値は二重引用符でくくられます。

F.18.2. hstoreの演算子と関数 #

<title><type>hstore</type> Operators and Functions</title>

The operators provided by the <literal>hstore</literal> module are shown in <xref linkend="hstore-op-table"/>, the functions in <xref linkend="hstore-func-table"/>. hstoreモジュールで提供される演算子を表 F.7に、関数を表 F.8に示します。

表F.7 hstoreの演算子

<title><type>hstore</type> Operators</title>

Operator 演算子

Description 説明

Example(s)

hstore -> texttext

Returns value associated with given key, or <literal>NULL</literal> if not present. 与えられたキーに対応する値を、存在しなければNULLを返します。

'a=>x, b=>y'::hstore -> 'a'x

hstore -> text[]text[]

Returns values associated with given keys, or <literal>NULL</literal> if not present. 与えられたキーに対応する値を、存在しなければNULLを返します。

'a=>x, b=>y, c=>z'::hstore -> ARRAY['c','a']{"z","x"}

hstore || hstorehstore

Concatenates two <type>hstore</type>s. 2つのhstoreを連結します。

'a=>b, c=>d'::hstore || 'c=>x, d=>q'::hstore"a"=>"b", "c"=>"x", "d"=>"q"

hstore ? textboolean

Does <type>hstore</type> contain key? hstoreがキーを含むか。

'a=>1'::hstore ? 'a't

hstore ?& text[]boolean

Does <type>hstore</type> contain all the specified keys? hstoreが指定したキーをすべて含むか。

'a=>1,b=>2'::hstore ?& ARRAY['a','b']t

hstore ?| text[]boolean

Does <type>hstore</type> contain any of the specified keys? hstoreが指定したキーのいずれかを含むか。

'a=>1,b=>2'::hstore ?| ARRAY['b','c']t

hstore @> hstoreboolean

Does left operand contain right? 左辺は右辺を含むか。

'a=>b, b=>1, c=>NULL'::hstore @> 'b=>1't

hstore <@ hstoreboolean

Is left operand contained in right? 左辺は右辺に含まれるか。

'a=>c'::hstore <@ 'a=>b, b=>1, c=>NULL'f

hstore - texthstore

Deletes key from left operand. 左辺からキーを削除します。

'a=>1, b=>2, c=>3'::hstore - 'b'::text"a"=>"1", "c"=>"3"

hstore - text[]hstore

Deletes keys from left operand. 左辺からキー(複数)を削除します。

'a=>1, b=>2, c=>3'::hstore - ARRAY['a','b']"c"=>"3"

hstore - hstorehstore

Deletes pairs from left operand that match pairs in the right operand. 右辺の組み合わせに一致する組み合わせを左辺から削除します。

'a=>1, b=>2, c=>3'::hstore - 'a=>4, b=>2'::hstore"a"=>"1", "c"=>"3"

anyelement #= hstoreanyelement

Replaces fields in the left operand (which must be a composite type) with matching values from <type>hstore</type>. 左辺(複合型でなければなりません)のフィールドをhstoreの対応する値で置換します。

ROW(1,3) #= 'f1=>11'::hstore(11,3)

%% hstoretext[]

Converts <type>hstore</type> to an array of alternating keys and values. hstoreをキーと値が交互に並んだ配列に変換します。

%% 'a=>foo, b=>bar'::hstore{a,foo,b,bar}

%# hstoretext[]

Converts <type>hstore</type> to a two-dimensional key/value array. hstoreをキーと値の2次元配列に変換します。

%# 'a=>foo, b=>bar'::hstore{{a,foo},{b,bar}}


表F.8 hstoreの関数

<title><type>hstore</type> Functions</title>

Function 関数

Description 説明

Example(s)

hstore ( record ) → hstore

Constructs an <type>hstore</type> from a record or row. レコードまたは行からhstoreを生成します。

hstore(ROW(1,2))"f1"=>"1", "f2"=>"2"

hstore ( text[] ) → hstore

Constructs an <type>hstore</type> from an array, which may be either a key/value array, or a two-dimensional array. 配列からhstoreを生成します。配列はキー、値の配列でも2次元の配列でも構いません。

hstore(ARRAY['a','1','b','2'])"a"=>"1", "b"=>"2"

hstore(ARRAY[['c','3'],['d','4']])"c"=>"3", "d"=>"4"

hstore ( text[], text[] ) → hstore

Constructs an <type>hstore</type> from separate key and value arrays. キー、値で分けた配列からhstoreを作成します。

hstore(ARRAY['a','b'], ARRAY['1','2'])"a"=>"1", "b"=>"2"

hstore ( text, text ) → hstore

Makes a single-item <type>hstore</type>. hstore型の単一項目を作成します。

hstore('a', 'b')"a"=>"b"

akeys ( hstore ) → text[]

Extracts an <type>hstore</type>'s keys as an array. hstoreのキーを配列として取り出します。

akeys('a=>1,b=>2'){a,b}

skeys ( hstore ) → setof text

Extracts an <type>hstore</type>'s keys as a set. hstoreのキーを集合として取り出します。

skeys('a=>1,b=>2')

a
b

avals ( hstore ) → text[]

Extracts an <type>hstore</type>'s values as an array. hstoreの値を配列として取り出します。

avals('a=>1,b=>2'){1,2}

svals ( hstore ) → setof text

Extracts an <type>hstore</type>'s values as a set. hstoreの値を集合として取り出します。

svals('a=>1,b=>2')

1
2

hstore_to_array ( hstore ) → text[]

Extracts an <type>hstore</type>'s keys and values as an array of alternating keys and values. hstoreのキーと値を、キーと値が交互に並んだ配列として取り出します。

hstore_to_array('a=>1,b=>2'){a,1,b,2}

hstore_to_matrix ( hstore ) → text[]

Extracts an <type>hstore</type>'s keys and values as a two-dimensional array. hstoreのキーと値を、2次元の配列として取り出します。

hstore_to_matrix('a=>1,b=>2'){{a,1},{b,2}}

hstore_to_json ( hstore ) → json

Converts an <type>hstore</type> to a <type>json</type> value, converting all non-null values to JSON strings. 非nullの値をすべてJSON文字列に変換しながら、hstorejson値に変換します。

This function is used implicitly when an <type>hstore</type> value is cast to <type>json</type>. この関数はhstore値がjsonにキャストされるときに暗黙的に使用されます。

hstore_to_json('"a key"=>1, b=>t, c=>null, d=>12345, e=>012345, f=>1.234, g=>2.345e+4'){"a key": "1", "b": "t", "c": null, "d": "12345", "e": "012345", "f": "1.234", "g": "2.345e+4"}

hstore_to_jsonb ( hstore ) → jsonb

Converts an <type>hstore</type> to a <type>jsonb</type> value, converting all non-null values to JSON strings. 非nullの値をすべてJSON文字列に変換しながら、hstorejsonb値に変換します。

This function is used implicitly when an <type>hstore</type> value is cast to <type>jsonb</type>. この関数はhstore値がjsonbにキャストされるときに暗黙的に使用されます。

hstore_to_jsonb('"a key"=>1, b=>t, c=>null, d=>12345, e=>012345, f=>1.234, g=>2.345e+4'){"a key": "1", "b": "t", "c": null, "d": "12345", "e": "012345", "f": "1.234", "g": "2.345e+4"}

hstore_to_json_loose ( hstore ) → json

Converts an <type>hstore</type> to a <type>json</type> value, but attempts to distinguish numerical and Boolean values so they are unquoted in the JSON. hstorejson値に変換します。ですが、数値およびブール値を識別しようとするため、その2つはJSON中では引用符が付きません。

hstore_to_json_loose('"a key"=>1, b=>t, c=>null, d=>12345, e=>012345, f=>1.234, g=>2.345e+4'){"a key": 1, "b": true, "c": null, "d": 12345, "e": "012345", "f": 1.234, "g": 2.345e+4}

hstore_to_jsonb_loose ( hstore ) → jsonb

Converts an <type>hstore</type> to a <type>jsonb</type> value, but attempts to distinguish numerical and Boolean values so they are unquoted in the JSON. hstorejsonb値に変換します。ですが、数値およびブール値を識別しようとするため、その2つはJSON中では引用符が付きません。

hstore_to_jsonb_loose('"a key"=>1, b=>t, c=>null, d=>12345, e=>012345, f=>1.234, g=>2.345e+4'){"a key": 1, "b": true, "c": null, "d": 12345, "e": "012345", "f": 1.234, "g": 2.345e+4}

slice ( hstore, text[] ) → hstore

Extracts a subset of an <type>hstore</type> containing only the specified keys. 指定されたキーだけを含むhstoreの部分集合を取り出します。

slice('a=>1,b=>2,c=>3'::hstore, ARRAY['b','c','x'])"b"=>"2", "c"=>"3"

each ( hstore ) → setof record ( key text, value text )

Extracts an <type>hstore</type>'s keys and values as a set of records. hstoreのキーと値をレコードの集合として取り出します。

select * from each('a=>1,b=>2')

 key | value
-----+-------
 a   | 1
 b   | 2

exist ( hstore, text ) → boolean

Does <type>hstore</type> contain key? hstoreがキーを含むか。

exist('a=>1', 'a')t

defined ( hstore, text ) → boolean

Does <type>hstore</type> contain a non-<literal>NULL</literal> value for key? hstoreがキーに対して非NULLの値を含むか。

defined('a=>NULL', 'a')f

delete ( hstore, text ) → hstore

Deletes pair with matching key. キーに一致する組み合わせを削除します。

delete('a=>1,b=>2', 'b')"a"=>"1"

delete ( hstore, text[] ) → hstore

Deletes pairs with matching keys. キー(複数)に一致する組み合わせを削除します。

delete('a=>1,b=>2,c=>3', ARRAY['a','b'])"c"=>"3"

delete ( hstore, hstore ) → hstore

Deletes pairs matching those in the second argument. 第2引数内の組み合わせと一致する組み合わせを削除します。

delete('a=>1,b=>2', 'a=>4,b=>2'::hstore)"a"=>"1"

populate_record ( anyelement, hstore ) → anyelement

Replaces fields in the left operand (which must be a composite type) with matching values from <type>hstore</type>. 左辺(複合型でなければなりません)のフィールドをhstoreの対応する値で置換します。

populate_record(ROW(1,2), 'f1=>42'::hstore)(42,2)


In addition to these operators and functions, values of the <type>hstore</type> type can be subscripted, allowing them to act like associative arrays. Only a single subscript of type <type>text</type> can be specified; it is interpreted as a key and the corresponding value is fetched or stored. For example, この演算子や関数に加えて、hstore型の値は添字を付けることができ、その場合、連想配列のように振る舞います。 text型の単一の添字のみが指定可能です。添字はキーとして解釈され、対応する値が取り出されたり、保存されたりします。 以下に例を示します。

CREATE TABLE mytable (h hstore);
INSERT INTO mytable VALUES ('a=>b, c=>d');
SELECT h['a'] FROM mytable;
 h
---
 b
(1 row)

UPDATE mytable SET h['c'] = 'new';
SELECT h FROM mytable;
          h
----------------------
 "a"=>"b", "c"=>"new"
(1 row)

A subscripted fetch returns <literal>NULL</literal> if the subscript is <literal>NULL</literal> or that key does not exist in the <type>hstore</type>. (Thus, a subscripted fetch is not greatly different from the <literal>-&gt;</literal> operator.) A subscripted update fails if the subscript is <literal>NULL</literal>; otherwise, it replaces the value for that key, adding an entry to the <type>hstore</type> if the key does not already exist. 添字がNULLの場合や、そのキーがhstore内に存在しない場合には、添字による取り出しはNULLを返します。 (ですので、添字による取り出しは->演算子とそれほど異なりません。) 添字がNULLの場合には、添字による更新は失敗します。そうでなければ、そのキーに対応する値を置き換え、キーがまだ存在していなければhstoreにエントリを追加します。

F.18.3. インデックス #

<title>Indexes</title>

<type>hstore</type> has GiST and GIN index support for the <literal>@&gt;</literal>, <literal>?</literal>, <literal>?&amp;</literal> and <literal>?|</literal> operators. For example: hstore@>??&および?|演算子向けのGiSTおよびGINインデックスをサポートします。 以下に例を示します。

CREATE INDEX hidx ON testhstore USING GIST (h);

CREATE INDEX hidx ON testhstore USING GIN (h);

<literal>gist_hstore_ops</literal> GiST opclass approximates a set of key/value pairs as a bitmap signature. Its optional integer parameter <literal>siglen</literal> determines the signature length in bytes. The default length is 16 bytes. Valid values of signature length are between 1 and 2024 bytes. Longer signatures lead to a more precise search (scanning a smaller fraction of the index and fewer heap pages), at the cost of a larger index. gist_hstore_ops GiST演算子クラスはキー/値の集合をビットマップ署名として近似します。 オプションの整数パラメータsiglenは、署名の長さをバイト単位で決定します。 デフォルトの署名の長さは16バイトです。 署名の長さの有効な値は1から2024バイトまでです。 長い署名では、インデックスはより大きくなってしまいますが、(インデックスのより小さな部分とより少ないヒープページを走査することで)検索がより正確になります。

Example of creating such an index with a signature length of 32 bytes: 署名の長さが32バイトのインデックスを作成する例

CREATE INDEX hidx ON testhstore USING GIST (h gist_hstore_ops(siglen=32));

<type>hstore</type> also supports <type>btree</type> or <type>hash</type> indexes for the <literal>=</literal> operator. This allows <type>hstore</type> columns to be declared <literal>UNIQUE</literal>, or to be used in <literal>GROUP BY</literal>, <literal>ORDER BY</literal> or <literal>DISTINCT</literal> expressions. The sort ordering for <type>hstore</type> values is not particularly useful, but these indexes may be useful for equivalence lookups. Create indexes for <literal>=</literal> comparisons as follows: hstoreはまた、=演算子向けにbtreeまたはhashインデックスをサポートします。 これによりhstoreの列をUNIQUEと宣言すること、また、GROUP BYORDER BYDISTINCTの式で使用することができます。 hstore値のソート順序付けはあまり有用ではありません。 しかしこれらのインデックスは同値検索の際に有用になるかもしれません。 =比較用のインデックスを以下のように作成します。

CREATE INDEX hidx ON testhstore USING BTREE (h);

CREATE INDEX hidx ON testhstore USING HASH (h);

F.18.4. 例 #

<title>Examples</title>

Add a key, or update an existing key with a new value: キーを追加、または、既存のキーを新しい値で更新します。

UPDATE tab SET h['c'] = '3';

Another way to do the same thing is: 同じことを行なう他の方法を以下に示します。

UPDATE tab SET h = h || hstore('c', '3');

If multiple keys are to be added or changed in one operation, the concatenation approach is more efficient than subscripting: 1つの操作で複数のキーを追加したり変更したりする場合には、連結する方が添字を使うよりも効率的です。

UPDATE tab SET h = h || hstore(array['q', 'w'], array['11', '12']);

Delete a key: キーを削除します。

UPDATE tab SET h = delete(h, 'k1');

Convert a <type>record</type> to an <type>hstore</type>: recordhstoreに変換します。

CREATE TABLE test (col1 integer, col2 text, col3 text);
INSERT INTO test VALUES (123, 'foo', 'bar');

SELECT hstore(t) FROM test AS t;
                   hstore
---------------------------------------------
 "col1"=>"123", "col2"=>"foo", "col3"=>"bar"
(1 row)

Convert an <type>hstore</type> to a predefined <type>record</type> type: hstoreを事前に定義されたrecord型に変換します。

CREATE TABLE test (col1 integer, col2 text, col3 text);

SELECT * FROM populate_record(null::test,
                              '"col1"=>"456", "col2"=>"zzz"');
 col1 | col2 | col3
------+------+------
  456 | zzz  |
(1 row)

Modify an existing record using the values from an <type>hstore</type>: hstoreの値を使用して既存のレコードを変更します。

CREATE TABLE test (col1 integer, col2 text, col3 text);
INSERT INTO test VALUES (123, 'foo', 'bar');

SELECT (r).* FROM (SELECT t #= '"col3"=>"baz"' AS r FROM test t) s;
 col1 | col2 | col3
------+------+------
  123 | foo  | baz
(1 row)

F.18.5. 統計情報 #

<title>Statistics</title>

The <type>hstore</type> type, because of its intrinsic liberality, could contain a lot of different keys. Checking for valid keys is the task of the application. The following examples demonstrate several techniques for checking keys and obtaining statistics. 内在する自由度のため、hstore型は異なるキーを多く含むことができます。 有効なキーを検査することはアプリケーション側の作業です。 以下の例では、キー検査および統計情報の入手に関する複数の技法を示します。

Simple example: 簡単な例を示します。

SELECT * FROM each('aaa=>bq, b=>NULL, ""=>1');

Using a table: テーブルを使用する例です。

CREATE TABLE stat AS SELECT (each(h)).key, (each(h)).value FROM testhstore;

Online statistics: オンライン統計値です。

SELECT key, count(*) FROM
  (SELECT (each(h)).key FROM testhstore) AS stat
  GROUP BY key
  ORDER BY count DESC, key;
    key    | count
-----------+-------
 line      |   883
 query     |   207
 pos       |   203
 node      |   202
 space     |   197
 status    |   195
 public    |   194
 title     |   190
 org       |   189
...................

F.18.6. 互換性 #

<title>Compatibility</title>

As of PostgreSQL 9.0, <type>hstore</type> uses a different internal representation than previous versions. This presents no obstacle for dump/restore upgrades since the text representation (used in the dump) is unchanged. PostgreSQL 9.0からhstoreの内部表現はこれまでから変更されました。 (ダンプ内で使用される)テキスト表現には変更がありませんので、ダンプ/リストアによる更新の妨げにはなりません。

In the event of a binary upgrade, upward compatibility is maintained by having the new code recognize old-format data. This will entail a slight performance penalty when processing data that has not yet been modified by the new code. It is possible to force an upgrade of all values in a table column by doing an <literal>UPDATE</literal> statement as follows: バイナリによる更新の際、新しいコードで古い書式のデータを認識させることにより、上位互換が保持されます。 これには、新しいコードによりまだ変更されていないデータを処理する際に、性能の劣化を多少伴います。 以下のようにUPDATE文を実行することによりテーブル列内のすべての値を強制的に更新することができます。

UPDATE tablename SET hstorecol = hstorecol || '';

Another way to do it is: 上を行う他の方法を以下に示します。

ALTER TABLE tablename ALTER hstorecol TYPE hstore USING hstorecol || '';

The <command>ALTER TABLE</command> method requires an <literal>ACCESS EXCLUSIVE</literal> lock on the table, but does not result in bloating the table with old row versions. ALTER TABLEによる方法はテーブルに対してACCESS EXCLUSIVEロックを必要とします。 しかし、古いバージョンの行でテーブルが膨張することはありません。

F.18.7. 変換 #

<title>Transforms</title>

Additional extensions are available that implement transforms for the <type>hstore</type> type for the languages PL/Perl and PL/Python. The extensions for PL/Perl are called <literal>hstore_plperl</literal> and <literal>hstore_plperlu</literal>, for trusted and untrusted PL/Perl. If you install these transforms and specify them when creating a function, <type>hstore</type> values are mapped to Perl hashes. The extension for PL/Python is called <literal>hstore_plpython3u</literal>. If you use it, <type>hstore</type> values are mapped to Python dictionaries. PL/Perl言語やPL/Python言語向けにhstore型の変換を実装した追加の拡張が入手可能です。 PL/Perl向けの拡張は、信頼されたPL/Perlに対してはhstore_plperlという名前で、信頼されないものに対してはhstore_plperluという名前です。 関数を作成するときにこの変換をインストールして指定していれば、hstoreの値はPerlのハッシュにマップされます。 PL/Python向けの拡張はhstore_plpython3uという名前です。 この拡張を使うとhstoreの値はPythonの辞書型にマップされます。

注意

It is strongly recommended that the transform extensions be installed in the same schema as <filename>hstore</filename>. Otherwise there are installation-time security hazards if a transform extension's schema contains objects defined by a hostile user. 変換の拡張はhstoreと同じスキーマにインストールすることを強く勧めます。 さもないと、変換の拡張のスキーマが悪意のあるユーザにより定義されたオブジェクトを含んでいた場合に、インストール時のセキュリティ問題になります。

F.18.8. 作者 #

<title>Authors</title>

Oleg Bartunov , Moscow, Moscow University, Russia

Teodor Sigaev , Moscow, Delta-Soft Ltd., Russia

Additional enhancements by Andrew Gierth <email>andrew@tao11.riddles.org.uk</email>, United Kingdom 追加の改良はAndrew Gierth ,United Kingdomによりなされました。