F.16. hstore

Этот модуль реализует тип данных hstore для хранения пар ключ/значение внутри одного значения Postgres Pro. Это может быть полезно в самых разных сценариях, например для хранения строк со множеством редко анализируемых атрибутов или частично структурированных данных. Ключи и значения задаются простыми текстовыми строками.

F.16.1. Внешнее представление hstore

Текстовое представление типа hstore, применяемое для ввода и вывода, включает ноль или более пар ключ => значение, разделённых запятыми. Несколько примеров:

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

Порядок пар не имеет значения (и может не воспроизводиться при выводе). Пробелы между парами и вокруг знака => игнорируются. Ключи и значения, содержащие пробелы, запятые и знаки = или >, нужно заключать в двойные кавычки. Если в ключ или значение нужно вставить символ кавычек или обратную косую черту, добавьте перед ним обратную косую черту.

Все ключи в hstore уникальны. Если вы объявите тип hstore с дублирующимися ключами, в hstore будет сохранён только один ключ без гарантии определённого выбора:

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

В качестве значения (но не ключа) может задаваться SQL NULL. Например:

key => NULL

В ключевом слове NULL регистр не имеет значения. Если требуется, чтобы текст NULL воспринимался как обычная строка «NULL», заключите его в кавычки.

Примечание

Учтите, что когда текстовый формат hstore используется для ввода данных, он применяется до обработки кавычек или спецсимволов. Таким образом, если значение hstore передаётся в параметре, дополнительная обработка не требуется. Но если вы передаёте его в виде строковой константы, то все символы апострофов и (в зависимости от параметра конфигурации standard_conforming_strings) обратной косой черты нужно корректно экранировать. Подробнее о записи строковых констант можно узнать в Подразделе 4.1.2.1.

При выводе значения и ключи всегда заключаются в кавычки, даже когда без этого можно обойтись.

F.16.2. Операторы и функции hstore

Реализованные в модуле hstore операторы перечислены в Таблице F.8, функции — в Таблице F.9.

Таблица F.8. Операторы hstore

ОператорОписаниеПримерРезультат
hstore -> textвыдаёт значение для ключа (или NULL при его отсутствии)'a=>x, b=>y'::hstore -> 'a'x
hstore -> text[]выдаёт значения для ключей (или NULL при их отсутствии)'a=>x, b=>y, c=>z'::hstore -> ARRAY['c','a']{"z","x"}
hstore || hstoreобъединяет два набора hstore'a=>b, c=>d'::hstore || 'c=>x, d=>q'::hstore"a"=>"b", "c"=>"x", "d"=>"q"
hstore ? textнабор hstore включает ключ?'a=>1'::hstore ? 'a't
hstore ?& text[]набор hstore включает все указанные ключи?'a=>1,b=>2'::hstore ?& ARRAY['a','b']t
hstore ?| text[]набор hstore включает какой-либо из указанных ключей?'a=>1,b=>2'::hstore ?| ARRAY['b','c']t
hstore @> hstoreлевый операнд включает правый?'a=>b, b=>1, c=>NULL'::hstore @> 'b=>1't
hstore <@ hstoreлевый операнд включён в правый?'a=>c'::hstore <@ 'a=>b, b=>1, c=>NULL'f
hstore - textудаляет ключ из левого операнда'a=>1, b=>2, c=>3'::hstore - 'b'::text"a"=>"1", "c"=>"3"
hstore - text[]удаляет ключи из левого операнда'a=>1, b=>2, c=>3'::hstore - ARRAY['a','b']"c"=>"3"
hstore - hstoreудаляет соответствующие пары из левого операнда'a=>1, b=>2, c=>3'::hstore - 'a=>4, b=>2'::hstore"a"=>"1", "c"=>"3"
record #= hstoreзаменяет поля в record соответствующими значениями из hstoreсм. раздел Примеры 
%% hstoreпреобразует hstore в массив перемежающихся ключей и значений%% 'a=>foo, b=>bar'::hstore{a,foo,b,bar}
%# hstoreпреобразует hstore в двумерный массив ключей/значений%# 'a=>foo, b=>bar'::hstore{{a,foo},{b,bar}}

Примечание

До версии PostgreSQL 8.2 операторы включения @> и <@ обозначались соответственно как @ и ~. Эти имена по-прежнему действуют, но считаются устаревшими и в конце концов будут упразднены. Заметьте, что старые имена произошли из соглашения, которому раньше следовали геометрические типы данных!

Таблица F.9. Функции hstore

ФункцияТип результатаОписаниеПримерРезультат
hstore(record)hstoreформирует hstore из записи или кортежаhstore(ROW(1,2))f1=>1,f2=>2
hstore(text[])hstoreформирует hstore из массива, который может содержать попарно ключи/значения, либо быть двумерным массивомhstore(ARRAY['a','1','b','2']) || hstore(ARRAY[['c','3'],['d','4']])a=>1, b=>2, c=>3, d=>4
hstore(text[], text[])hstoreформирует hstore из отдельных массивов ключей и значенийhstore(ARRAY['a','b'], ARRAY['1','2'])"a"=>"1","b"=>"2"
hstore(text, text)hstoreформирует hstore с одним элементомhstore('a', 'b')"a"=>"b"
akeys(hstore)text[]выдаёт ключи hstore в виде массиваakeys('a=>1,b=>2'){a,b}
skeys(hstore)setof textвыдаёт ключи hstore в виде множестваskeys('a=>1,b=>2')
a
b
avals(hstore)text[]выдаёт ключи hstore в виде массиваavals('a=>1,b=>2'){1,2}
svals(hstore)setof textвыдаёт значения hstore в виде множестваsvals('a=>1,b=>2')
1
2
hstore_to_array(hstore)text[]выдаёт ключи и значения hstore в виде массива перемежающихся ключей и значенийhstore_to_array('a=>1,b=>2'){a,1,b,2}
hstore_to_matrix(hstore)text[]выдаёт ключи и значения hstore в виде двумерного массиваhstore_to_matrix('a=>1,b=>2'){{a,1},{b,2}}
hstore_to_json(hstore)jsonвыдаёт hstore в виде значения json, преобразуя все отличные от NULL значения в строки JSONhstore_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выдаёт hstore в виде значения jsonb, преобразуя все отличные от NULL значения в строки JSONhstore_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выдаёт hstore в виде значения json, по возможности распознавая числовые и логические значения и передавая их в 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выдаёт hstore в виде значения jsonb, по возможности распознавая числовые и логические значения и передавая их в 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извлекает подмножество из hstoreslice('a=>1,b=>2,c=>3'::hstore, ARRAY['b','c','x'])"b"=>"2", "c"=>"3"
each(hstore)setof(key text, value text)выдаёт ключи и значения hstore в виде множестваselect * from each('a=>1,b=>2')
 key | value
-----+-------
 a   | 1
 b   | 2
exist(hstore,text)booleanнабор hstore включает ключ?exist('a=>1','a')t
defined(hstore,text)booleanнабор hstore включает для ключа значение, отличное от NULL?defined('a=>NULL','a')f
delete(hstore,text)hstoreудаляет пару с соответствующим ключомdelete('a=>1,b=>2','b')"a"=>"1"
delete(hstore,text[])hstoreудаляет пары с соответствующими ключамиdelete('a=>1,b=>2,c=>3',ARRAY['a','b'])"c"=>"3"
delete(hstore,hstore)hstoreудаляет пары, соответствующие парам во втором аргументеdelete('a=>1,b=>2','a=>4,b=>2'::hstore)"a"=>"1"
populate_record(record,hstore)recordзаменяет поля в record соответствующими значениями из hstoreсм. раздел Примеры 

Примечание

Функция hstore_to_json применяется, когда значение hstore нужно привести к json. Подобным образом, hstore_to_jsonb применяется, когда значение hstore нужно привести к jsonb.

Примечание

Функция populate_record на самом деле объявлена как принимающая в первом аргументе anyelement, а не record, но если ей будет передан не тип записи, она выдаст ошибку.

F.16.3. Индексы

Тип hstore поддерживает индексы GiST и GIN для операторов @>, ?, ?& и ?|. Например:

CREATE INDEX hidx ON testhstore USING GIST (h);

CREATE INDEX hidx ON testhstore USING GIN (h);

Тип hstore также поддерживает индексы btree и hash для оператора =. Это позволяет объявлять столбцы hstore как уникальные (UNIQUE) и использовать их в выражениях GROUP BY, ORDER BY или DISTINCT. Порядок сортировки значений hstore не имеет практического смысла, но эти индексы могут быть полезны для поиска по равенству. Индексы для сравнений (с помощью =) можно создать так:

CREATE INDEX hidx ON testhstore USING BTREE (h);

CREATE INDEX hidx ON testhstore USING HASH (h);

F.16.4. Примеры

Добавление ключа или изменение значения для существующего ключа:

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

Удаление ключа:

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

Приведение типа record к типу hstore:

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)

Приведение типа 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)

Изменение существующей записи по данным из 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.16.5. Статистика

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

Простой пример:

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

С таблицей:

SELECT (each(h)).key, (each(h)).value INTO stat FROM testhstore;

Актуальная статистика:

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.16.6. Совместимость

Начиная с PostgreSQL 9.0, hstore использует внутреннее представление, отличающееся от предыдущих версий. Это не проблема при обновлении путём выгрузки/перезагрузки данных, так как текстовое представление (используемое при выгрузке) не меняется.

В случае двоичного обновления обратная совместимость поддерживается благодаря тому, что новый код понимает данные в старом формате. При таком обновлении возможно небольшое снижение производительности при обработке данных, которые ещё не были изменены новым кодом. Все значения в столбце таблицы можно обновить принудительно, выполнив следующий оператор UPDATE:

UPDATE tablename SET hstorecol = hstorecol || '';

Это можно сделать и так:

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

Вариант с командой ALTER TABLE требует расширенной блокировки таблицы, но не приводит к замусориванию таблицы старыми версиями строк.

F.16.7. Трансформации

Также имеются дополнительные расширения, реализующие трансформации типа hstore для языков PL/Perl и PL/Python. Расширения для PL/Perl называются hstore_plperl и hstore_plperlu для доверенного и недоверенного PL/Perl, соответственно. Если вы установите эти трансформации и укажете их при создании функции, значения hstore будут отображаться в хеши Perl. Расширения для PL/Python называются hstore_plpythonu, hstore_plpython2u и hstore_plpython3u (соглашения об именовании, принятые для интерфейса PL/Python, описаны в Разделе 43.1). Если вы воспользуетесь ими, значения hstore будут отображаться в словари Python.

F.16.8. Авторы

Олег Бартунов , Москва, Московский Государственный Университет, Россия

Фёдор Сигаев , Москва, ООО «Дельта-Софт», Россия

Дополнительные улучшения внёс Эндрю Гирт , Великобритания

F.16. hstore

This module implements the hstore data type for storing sets of key/value pairs within a single Postgres Pro 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.

F.16.1. hstore External Representation

The text representation of an hstore, used for input and output, includes zero or more key => value pairs separated by commas. Some examples:

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 => sign is ignored. Double-quote keys and values that include whitespace, commas, =s or >s. To include a double quote or a backslash in a key or value, escape it with a backslash.

Each key in an hstore is unique. If you declare an hstore with duplicate keys, only one will be stored in the hstore and there is no guarantee as to which will be kept:

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

A value (but not a key) can be an SQL NULL. For example:

key => NULL

The NULL keyword is case-insensitive. Double-quote the NULL to treat it as the ordinary string NULL.

Note

Keep in mind that the hstore text format, when used for input, applies before any required quoting or escaping. If you are passing an hstore 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 standard_conforming_strings configuration parameter) backslash characters need to be escaped correctly. See Section 4.1.2.1 for more on the handling of string constants.

On output, double quotes always surround keys and values, even when it's not strictly necessary.

F.16.2. hstore Operators and Functions

The operators provided by the hstore module are shown in Table F.8, the functions in Table F.9.

Table F.8. hstore Operators

OperatorDescriptionExampleResult
hstore -> textget value for key (NULL if not present)'a=>x, b=>y'::hstore -> 'a'x
hstore -> text[]get values for keys (NULL if not present)'a=>x, b=>y, c=>z'::hstore -> ARRAY['c','a']{"z","x"}
hstore || hstoreconcatenate hstores'a=>b, c=>d'::hstore || 'c=>x, d=>q'::hstore"a"=>"b", "c"=>"x", "d"=>"q"
hstore ? textdoes hstore contain key?'a=>1'::hstore ? 'a't
hstore ?& text[]does hstore contain all specified keys?'a=>1,b=>2'::hstore ?& ARRAY['a','b']t
hstore ?| text[]does hstore contain any of the specified keys?'a=>1,b=>2'::hstore ?| ARRAY['b','c']t
hstore @> hstoredoes left operand contain right?'a=>b, b=>1, c=>NULL'::hstore @> 'b=>1't
hstore <@ hstoreis left operand contained in right?'a=>c'::hstore <@ 'a=>b, b=>1, c=>NULL'f
hstore - textdelete key from left operand'a=>1, b=>2, c=>3'::hstore - 'b'::text"a"=>"1", "c"=>"3"
hstore - text[]delete keys from left operand'a=>1, b=>2, c=>3'::hstore - ARRAY['a','b']"c"=>"3"
hstore - hstoredelete matching pairs from left operand'a=>1, b=>2, c=>3'::hstore - 'a=>4, b=>2'::hstore"a"=>"1", "c"=>"3"
record #= hstorereplace fields in record with matching values from hstoresee Examples section 
%% hstoreconvert hstore to array of alternating keys and values%% 'a=>foo, b=>bar'::hstore{a,foo,b,bar}
%# hstoreconvert hstore to two-dimensional key/value array%# 'a=>foo, b=>bar'::hstore{{a,foo},{b,bar}}

Note

Prior to PostgreSQL 8.2, the containment operators @> and <@ were called @ and ~, respectively. These names are still available, but are deprecated and will eventually be removed. Notice that the old names are reversed from the convention formerly followed by the core geometric data types!

Table F.9. hstore Functions

FunctionReturn TypeDescriptionExampleResult
hstore(record)hstoreconstruct an hstore from a record or rowhstore(ROW(1,2))f1=>1,f2=>2
hstore(text[])hstoreconstruct an hstore from an array, which may be either a key/value array, or a two-dimensional arrayhstore(ARRAY['a','1','b','2']) || hstore(ARRAY[['c','3'],['d','4']])a=>1, b=>2, c=>3, d=>4
hstore(text[], text[])hstoreconstruct an hstore from separate key and value arrayshstore(ARRAY['a','b'], ARRAY['1','2'])"a"=>"1","b"=>"2"
hstore(text, text)hstoremake single-item hstorehstore('a', 'b')"a"=>"b"
akeys(hstore)text[]get hstore's keys as an arrayakeys('a=>1,b=>2'){a,b}
skeys(hstore)setof textget hstore's keys as a setskeys('a=>1,b=>2')
a
b
avals(hstore)text[]get hstore's values as an arrayavals('a=>1,b=>2'){1,2}
svals(hstore)setof textget hstore's values as a setsvals('a=>1,b=>2')
1
2
hstore_to_array(hstore)text[]get hstore's keys and values as an array of alternating keys and valueshstore_to_array('a=>1,b=>2'){a,1,b,2}
hstore_to_matrix(hstore)text[]get hstore's keys and values as a two-dimensional arrayhstore_to_matrix('a=>1,b=>2'){{a,1},{b,2}}
hstore_to_json(hstore)jsonget hstore as a json value, converting all non-null values to JSON stringshstore_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)jsonbget hstore as a jsonb value, converting all non-null values to JSON stringshstore_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)jsonget hstore as a json value, but attempt to distinguish numerical and Boolean values so they are unquoted in the JSONhstore_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)jsonbget hstore as a jsonb value, but attempt to distinguish numerical and Boolean values so they are unquoted in the JSONhstore_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[])hstoreextract a subset of an hstoreslice('a=>1,b=>2,c=>3'::hstore, ARRAY['b','c','x'])"b"=>"2", "c"=>"3"
each(hstore)setof(key text, value text)get hstore's keys and values as a setselect * from each('a=>1,b=>2')
 key | value
-----+-------
 a   | 1
 b   | 2
exist(hstore,text)booleandoes hstore contain key?exist('a=>1','a')t
defined(hstore,text)booleandoes hstore contain non-NULL value for key?defined('a=>NULL','a')f
delete(hstore,text)hstoredelete pair with matching keydelete('a=>1,b=>2','b')"a"=>"1"
delete(hstore,text[])hstoredelete pairs with matching keysdelete('a=>1,b=>2,c=>3',ARRAY['a','b'])"c"=>"3"
delete(hstore,hstore)hstoredelete pairs matching those in the second argumentdelete('a=>1,b=>2','a=>4,b=>2'::hstore)"a"=>"1"
populate_record(record,hstore)recordreplace fields in record with matching values from hstoresee Examples section 

Note

The function hstore_to_json is used when an hstore value is cast to json. Likewise, hstore_to_jsonb is used when an hstore value is cast to jsonb.

Note

The function populate_record is actually declared with anyelement, not record, as its first argument, but it will reject non-record types with a run-time error.

F.16.3. Indexes

hstore has GiST and GIN index support for the @>, ?, ?& and ?| operators. For example:

CREATE INDEX hidx ON testhstore USING GIST (h);

CREATE INDEX hidx ON testhstore USING GIN (h);

hstore also supports btree or hash indexes for the = operator. This allows hstore columns to be declared UNIQUE, or to be used in GROUP BY, ORDER BY or DISTINCT expressions. The sort ordering for hstore values is not particularly useful, but these indexes may be useful for equivalence lookups. Create indexes for = comparisons as follows:

CREATE INDEX hidx ON testhstore USING BTREE (h);

CREATE INDEX hidx ON testhstore USING HASH (h);

F.16.4. Examples

Add a key, or update an existing key with a new value:

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

Delete a key:

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

Convert a record to an hstore:

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 hstore to a predefined record type:

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 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.16.5. Statistics

The hstore 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.

Simple example:

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

Using a table:

SELECT (each(h)).key, (each(h)).value INTO stat 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.16.6. Compatibility

As of PostgreSQL 9.0, hstore 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.

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 UPDATE statement as follows:

UPDATE tablename SET hstorecol = hstorecol || '';

Another way to do it is:

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

The ALTER TABLE method requires an exclusive lock on the table, but does not result in bloating the table with old row versions.

F.16.7. Transforms

Additional extensions are available that implement transforms for the hstore type for the languages PL/Perl and PL/Python. The extensions for PL/Perl are called hstore_plperl and hstore_plperlu, for trusted and untrusted PL/Perl. If you install these transforms and specify them when creating a function, hstore values are mapped to Perl hashes. The extensions for PL/Python are called hstore_plpythonu, hstore_plpython2u, and hstore_plpython3u (see Section 43.1 for the PL/Python naming convention). If you use them, hstore values are mapped to Python dictionaries.

F.16.8. Authors

Oleg Bartunov , Moscow, Moscow University, Russia

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

Additional enhancements by Andrew Gierth , United Kingdom

FAQ