这个模块实现了hstore数据类型用来在一个单一PostgreSQL值中存储键值对,模板如:key=>value,key代表存储的属性,values为相应属性对应的值。键和值都是简单的文本字符串。
hstore外部表示
一个hstore文本表示用于输入和输出。每一个键是唯一的且键值对的顺序没有意义。
test=# select 'a=>1,a=>2,b=>3,c=>null,d=>NULL'::hstore;
hstore
------------------------------------------
"a"=>"1", "b"=>"3", "c"=>NULL, "d"=>NULL
(1 行记录)
hstore常用操作符
查询key对应的值
test=# select hstore('a=>1,b=>2') -> 'a';
?column?
----------
1
(1 行记录)
判断是否包含指定key
test=# select hstore('a=>c,b=>d') ? 'a';
?column?
----------
t
(1 行记录)
test=# select hstore('a=>c,b=>d') ? 'c';
?column?
----------
f
(1 行记录)
判断左边的hstore是否包含右边的hstore
test=# select 'a=>2,b=>3'::hstore @> 'a=>2'::hstore;
?column?
----------
t
(1 行记录)
test=# select 'a=>2,b=>3'::hstore @> 'a=>4'::hstore;
?column?
----------
f
(1 行记录)
串接hstore
test=# select hstore('a=>1') || 'b=>2'::hstore;
?column?
--------------------
"a"=>"1", "b"=>"2"
(1 行记录)
hstore常用函数
array类型转换为hstore类型
test=# select hstore(array['a','1','b','2']);
hstore
--------------------
"a"=>"1", "b"=>"2"
(1 行记录)
将两个array类型转换为hstore类型
test=# select hstore(array['a','b','c'],array['1','2','3']);
hstore
------------------------------
"a"=>"1", "b"=>"2", "c"=>"3"
(1 行记录)
将hstore类型数据的key转换为array
test=# select akeys('a=>1,b=>2');
akeys
-------
{a,b}
(1 行记录)
将hstore类型数据的key转换为结果集
test=# select skeys('a=>1,b=>2');
skeys
-------
a
b
(2 行记录)
将hstore类型数据的values转换为array
test=# select avals('a=>1,b=>2');
avals
-------
{1,2}
(1 行记录)
将hstore类型数据的values转换为结果集
test=# select svals('a=>1,b=>2');
svals
-------
1
2
(2 行记录)
删除一个属性
test=# select delete(hstore('a=>1,b=>2'),'b');
delete
----------
"a"=>"1"
(1 行记录)
hstore综合使用
test=# create table test(id serial,info hstore);
CREATE TABLE
test=# insert into test(info) values('age=>1,grade=>2'::hstore),('age=>3,grade=>4'::hstore),('age=>5,grade=>6'::hstore);
INSERT 0 3
test=# select * from test;
id | info
----+--------------------------
1 | "age"=>"1", "grade"=>"2"
2 | "age"=>"3", "grade"=>"4"
3 | "age"=>"5", "grade"=>"6"
(3 行记录)
创建索引
test=# create index idx_test_info on test using GIST(info);
CREATE INDEX
注:hstore类型的数据支持GIN,GIST索引扫描的操作符有@>,?,?&,和?|
test=# update test set info = info || 'gendre=>male'::hstore;
UPDATE 3
test=# select * from test;
id | info
----+--------------------------------------------
1 | "age"=>"1", "grade"=>"2", "gendre"=>"male"
2 | "age"=>"3", "grade"=>"4", "gendre"=>"male"
3 | "age"=>"5", "grade"=>"6", "gendre"=>"male"
(3 行记录)
将结果集转换为hstore类型输出
test=# select hstore(test) from test;
hstore
-----------------------------------------------------------------------------
"id"=>"1", "info"=>"\"age\"=>\"1\", \"grade\"=>\"2\", \"gendre\"=>\"male\""
"id"=>"2", "info"=>"\"age\"=>\"3\", \"grade\"=>\"4\", \"gendre\"=>\"male\""
"id"=>"3", "info"=>"\"age\"=>\"5\", \"grade\"=>\"6\", \"gendre\"=>\"male\""
(3 行记录)
注:要在一个值或键中包括一个双引号或一个 反斜线,用一个反斜线对它转义。