DROP DATABASE IF EXISTS books_db; CREATE DATABASE books_db WITH ENCODING='UTF8' TEMPLATE template0; DROP TABLE IF EXISTS books; CREATE TABLE books ( id SERIAL PRIMARY KEY, client TEXT NOT NULL, data JSONb NOT NULL );
INSERT INTO books(client, data) values ( 'Joe', '{ "title": "Siddhartha", "author": { "first_name": "Herman", "last_name": "Hesse" } }' ),( 'Jenny', '{ "title": "Dharma Bums", "author": { "first_name": "Jack", "last_name": "Kerouac" } }' ),( 'Jenny', '{ "title": "100 años de soledad", "author": { "first_name": "Gabo", "last_name": "Marquéz" } }' );
让我们看一下表格中的所有内容:
SELECT * FROM books;
输出:
选择1列:
SELECT client, data->'title' AS title FROM books;
输出:
选择2列:
SELECT client, data->'title' AS title, data->'author' AS author FROM books;
输出:
该->运算符返回原始JSON类型(可能是一个对象),而->>返回文本。
您可以使用->返回一个嵌套对象,从而链接运算符:
SELECT client, data->'author'->'last_name' AS author FROM books;
输出:
根据JSON中的值选择行:
SELECT client, data->'title' AS title FROM books WHERE data->'title' = '"Dharma Bums"';
注意WHERE使用的,->所以我们必须与JSON进行比较'"Dharma Bums"'
或者我们可以使用->>和比较'Dharma Bums'
输出:
根据嵌套JSON对象的值查找行:
SELECT client, data->'title' AS title FROM books WHERE data->'author'->>'last_name' = 'Kerouac';
输出:
CREATE TABLE events ( name varchar(200), visitor_id varchar(200), properties json, browser json );
我们将在此表中存储事件,例如浏览量。每个事件都有属性,可以是任何属性(例如当前页面),还可以发送有关浏览器的信息(例如OS,屏幕分辨率等)。两者都是完全免费的形式,并且可能会随着时间的流逝而发生变化(因为我们认为需要跟踪更多的内容)。
INSERT INTO events (name, visitor_id, properties, browser) VALUES ( 'pageview', '1', '{ "page": "/" }', '{ "name": "Chrome", "os": "Mac", "resolution": { "x": 1440, "y": 900 } }' ),( 'pageview', '2', '{ "page": "/" }', '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1920, "y": 1200 } }' ),( 'pageview', '1', '{ "page": "/account" }', '{ "name": "Chrome", "os": "Mac", "resolution": { "x": 1440, "y": 900 } }' ),( 'purchase', '5', '{ "amount": 10 }', '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1024, "y": 768 } }' ),( 'purchase', '15', '{ "amount": 200 }', '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1280, "y": 800 } }' ),( 'purchase', '15', '{ "amount": 500 }', '{ "name": "Firefox", "os": "Windows", "resolution": { "x": 1280, "y": 800 } }' );
现在让我们选择所有内容:
SELECT * FROM events;
输出:
使用JSON运算符,结合传统的PostgreSQL聚合函数,我们可以提取所需的任何内容。您可以随意使用RDBMS。
让我们看看浏览器的用法:
SELECT browser->>'name' AS browser,
count(browser)
FROM events
GROUP BY browser->>'name';
输出:
每位访客的总收入:
SELECT visitor_id, SUM(CAST(properties->>'amount' AS integer)) AS total
FROM events
WHERE CAST(properties->>'amount' AS integer) > 0
GROUP BY visitor_id;
输出:
平均屏幕分辨率
SELECT AVG(CAST(browser->'resolution'->>'x' AS integer)) AS width,
AVG(CAST(browser->'resolution'->>'y' AS integer)) AS height
FROM events;
输出:
此处和此处有更多示例和文档。