hstore
是一个 contrib 模块,提供了一种存储键值对的数据类型(hstore
)。这使得可以在单个 PostgreSQL 值中存储一组键值对。
hstore
在 PostgreSQL 8.2 中被添加。
安装
假设 hstore 模块在您的系统上可用,请(以超级用户身份)将其安装到要使用它的数据库中
CREATE EXTENSION hstore;
请注意,此扩展会在其创建的模式中安装大量函数(截至 PostgreSQL 12 时为 58 个),因此最好使用以下方式将其安装到专用模式中:
CREATE EXTENSION hstore SCHEMA someschema;
变更历史
进行中
- PostgreSQL 14
- 支持对
hstore
值进行下标访问(提交 0ec5f7e7)
- 支持对
- PostgreSQL 13
- PostgreSQL 9.4 (1.3)
- 添加了以下函数(提交 d9134d0a)
hstore_to_jsonb()
hstore_to_jsonb_loose()
- 添加了以下函数(提交 d9134d0a)
- PostgreSQL 9.3
- 添加了以下函数(提交 38fb4d97)
hstore_to_json()
hstore_to_json_loose()
- 添加了以下函数(提交 38fb4d97)
- PostgreSQL 9.1 (1.0)
- 转换为扩展(提交 629b3af2)
- PostgreSQL 8.3
- PostgreSQL 8.2
- 添加(提交 642194ba)
示例
一个简单的 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