hstore

一个提供键值对存储数据类型的contrib模块

hstore 是一个 contrib 模块,提供了一种存储键值对的数据类型(hstore)。这使得可以在单个 PostgreSQL 值中存储一组键值对。

hstorePostgreSQL 8.2 中被添加。

安装

假设 hstore 模块在您的系统上可用,请(以超级用户身份)将其安装到要使用它的数据库中

CREATE EXTENSION hstore;

请注意,此扩展会在其创建的模式中安装大量函数(截至 PostgreSQL 12 时为 58 个),因此最好使用以下方式将其安装到专用模式中:

CREATE EXTENSION hstore SCHEMA someschema;

变更历史

进行中

示例

一个简单的 hstore 用法示例

testdb=# CREATE TABLE hstore_test(id SERIAL, val HSTORE);
NOTICE:  CREATE TABLE will create implicit sequence "hstore_test_id_seq" for serial column "hstore_test.id"
CREATE TABLE
testdb=# INSERT INTO hstore_test VALUES(DEFAULT, 'foo=>"bar"');
INSERT 0 1
testdb=# SELECT * from hstore_test;
 id |     val      
----+--------------
  1 | "foo"=>"bar"
(1 row)
向 HSTORE 追加值
testdb=# UPDATE hstore_test SET val = val || 'a=>"b"' WHERE id=1;
UPDATE 1
testdb=# SELECT * FROM hstore_test ;
 id |          val           
----+------------------------
  1 | "a"=>"b", "foo"=>"bar"
(1 row)

或者

testdb=# UPDATE hstore_test SET val = val || hstore('fish','finger') WHERE id=1;
UPDATE 1
testdb=# SELECT * FROM hstore_test;
 id | val 
----+------------------------
  1 | "a"=>"b", "foo"=>"bar", "fish"=>"finger"
(1 row)
在 HSTORE 中查找值
testdb=# SELECT id, val FROM hstore_test WHERE val->'foo' ='bar'; 
 id |          val           
----+------------------------
  1 | "a"=>"b", "foo"=>"bar", "fish"=>"finger"
(1 row)
将 HSTORE 的键/值检索为集合
testdb=# SELECT * FROM EACH((SELECT val FROM hstore_test));
 key  | value  
------+--------
 x    | y
 foo  | bar
 fish | finger
(3 rows)
从 HSTORE 中删除值
testdb=*# UPDATE hstore_test SET val = val - 'x'::TEXT;
UPDATE 1
testdb=*# SELECT * from hstore_test;
 id |               val        
----+--------------------------------
  2 | "foo"=>"bar", "fish"=>"finger"
(1 row)
从 HSTORE 中删除匹配的键/值对
testdb=*# UPDATE hstore_test SET val = val - 'fish => finger'::hstore;
UPDATE 1
testdb=*# SELECT * from hstore_test;
 id |      val 
----+---------------
  2 | "foo"=>"bar", 
(1 row)
在 HSTORE 的键上创建索引
CREATE INDEX index_foo ON hstore_test((val->'foo'));
  • PostgreSQL documentation: hstore

分类

Contrib 模块, 数据类型

另请参阅

hstore_plperl, hstore_plpython, hstore 技巧

反馈

提交关于“hstore”的任何评论、建议或更正请在此处 提交