PostgreSQL hstore: 保存json结构数据

Postgre支持的数据类型非常丰富, 可以储存 mac地址 ip地址 path路径 数组 等类型.
大家可能用到的情况不是很多, 不过有种数据结构你可能会需要 hash类型

datatype.png

hstore 储存的结构类似于MongoDB, 想体验nosql的便利, 可以用用hstore啊

开启 hstore extension

CREATE EXTENSION hstore;

表结构

CREATE TABLE books (
 id serial primary key,
 title VARCHAR (255),
 attr hstore
);

插入数据

INSERT INTO books (title, attr)
VALUES
 (
 'PostgreSQL Tutorial',

  '
    "paperback" => "243",
    "publisher" => "postgresqltutorial.com",
    "language"  => "English",
    "ISBN-13"   => "978-1449370000",
    "weight"    => "11.2 ounces"
  '
);

------

-- "author" => "shooter" 多了个作者

INSERT INTO books (title, attr)
VALUES
(
 'PostgreSQL Cheat Sheet',
 '
  "author" => "shooter",
  "paperback" => "5",
  "publisher" => "postgresqltutorial.com",
  "language"  => "English",
  "ISBN-13"   => "978-1449370001",
  "weight"    => "1 ounces"
 '
);

查询

SELECT attr FROM books; -- 普通查询

SELECT
 attr -> 'weight' AS weight
FROM
 books
WHERE
 attr -> 'ISBN-13' = '978-1449370000';

SELECT
 title
FROM
 books
WHERE
 attr @> '"weight"=>"11.2 ounces"' :: hstore;

更新

UPDATE books
SET attr = attr || '"freeshipping"=>"yes"' :: hstore;

UPDATE books
SET   attr = '"author"=>"shooter"' :: hstore;

删除属性

UPDATE books 
SET attr = delete(attr, 'freeshipping');

hstore 跟json/jsonb的 性能差异,在用了后在说吧


参考:
Use unstructured datatypes Hstore vs JSON vs JSONB

http://chenxiaoyu.org/2013/11/28/postgresql-array/
http://www.postgresqltutorial.com/postgresql-hstore/
https://www.zhihu.com/question/20010554/answer/62628256

https://my.oschina.net/swuly302/blog/143746 2013年翻译的文章 只供参考