10. オブジェクトの中身を参照
select (obj->>'id')::integer as id
, obj->>'title' as title
, obj->>'created_at' as created_at
, obj->'tags'->>0 as first_tag
from post_json
;
-- 演算子 -> , ->> でオブジェクトや配列の中身
にアクセス
11. オブジェクトの中身を参照
id | title | created_at | first_tag
----+----------------------------+--------------------------------+-----------
1 | すごいH本読んだ | 2015-08-16T14:10:02Z | book
2 | Dockerがどっかーにいった件 | Wed Oct 14 13:50:09 +0000 2015 | docker
3 | SchemeかわいいよScheme | 2015-10-16T14:10:02+09 | lisp
(3 rows)
14. B-Tree Indexをそのまま張るのはNG
create index post_json_obj
on post_json using btree (obj);
create index comment_json_obj
on comment_json using btree (obj);
-- obj全体を = で比較する場合しかindexが使われない
15. 式Index
create index post_json_id
on post_json using btree ((obj->>'id'));
create index comment_json_post_id
on comment_json using btree ((obj->>'post_id'));
16. Key名が決まらないならGIN※を
使おう
create index post_json_gin
on post_json using gin (obj jsonb_path_ops);
create index post_json_tags_gin
on post_json using gin (obj->'tags');
-- 配列に対するindexも貼れる
(※ GIN = Generalized Inverted Index)
20. SchemafulなテーブルへのINSERT
create table post (
id integer
, tags jsonb -- flatに出来ないものはjsonbに突っ込んじゃう
, title text
, created_at timestamptz
);
insert into post
select (jsonb_populate_record(null::post, obj)).*
from post_json
;
select *
from post;
25. こんなクエリを実行すると
with recursive eval as (
select obj->>'car' as car
, obj->'cdr' as cdr
, 1 as depth
from lisp
union all
select cdr->>'car' as car
, cdr->'cdr' as cdr
, depth + 1 as depth
from eval
where (cdr->'cdr') is not null
)
select string_agg(car, '' order by depth) as msg
from eval
;
(https://gist.github.com/yuki-takeichi/c4812f7af46f7f84e958)