What can you do with PostgreSQL and JSON?

What can you do with PostgreSQL and JSON?,第1张

概述PostgreSQL 9.2 added a native JSON data type, but didn’t add much else. You’ve got three options if you actually want to do something with it: Wait for PostgreSQL 9.3 (or use the beta) Use the plv8 ex


Postgresql 9.2 added a nativeJsONdata type,but dIDn’t add much else. You’ve got three options if you actually want to do something with it:

Wait for Postgresql 9.3 (or use the beta) Use theplv8extension. ValID option,but more DIY (you’ll have to define your own functions) Use theJson_enhancementsextension,which backports the new JsON functionality in 9.3 to 9.2

I wanted to use this stuffNow,and I opted to go with option 3. I wrote a blog post which should help you get going if you want to go this route:adding json_enhancements to PostgreSQL 9.2.

So let’s assume you’re on either 9.3,or 9.2 withJson_enhancements. What can you do?Lots!All the new JsON operators and functions are in the9.3 documentation,so I’m going to run through some of the more fun things you can do along with a real-world use case.

Get started

Create a database to play about in:


createdb Json_testpsql Json_test




With some sample data:


CREATE table books ( ID integer,data Json ); INSERT INTO books VALUES (1,'{ "name": "Book the First","author": { "first_name": "Bob","last_name": "White" } }'); INSERT INTO books VALUES (2,'{ "name": "Book the Second","author": { "first_name": "Charles","last_name": "XavIEr" } }'); INSERT INTO books VALUES (3,'{ "name": "Book the Third","author": { "first_name": "Jim","last_name": "brown" } }');



Selecting

You can use the JsON operators to pull values out of JsON columns:


SELECT ID,data->>'name' AS name FROM books; ID | name ----+-----------------  1 | Book the First 2 | Book the Second 3 | Book the Third



The->operator returns the original JsON type (which might be an object),whereas->>returns text. You can use the->to return a nested object and thus chain the operators:

SELECT ID,data->'author'->>'first_name' as author_first_name FROM books; ID | author_first_name ----+-------------------  1 | Bob 2 | Charles 3 | Jim



How cool is that?

Filtering

Of course,you can also select rows based on a value insIDe your JsON:


SELECT * FROM books WHERE data->>'name' = 'Book the First'; ID | data ----+---------------------------------------------------------------------------------------  1 | '{ "name": "Book the First","last_name": "White" } }'



You can also find rows based on the value of a nested JsON object:


SELECT * FROM books WHERE data->'author'->>'first_name' = 'Charles'; ID | data ----+---------------------------------------------------------------------------------------------  2 | '{ "name": "Book the Second","last_name": "XavIEr" } }'



Indexing

You can add indexes on any of these using Postgresql’sexpression indexes,which means you can even add unique constraints based on your nested JsON data:


CREATE UNIQUE INDEX books_author_first_name ON books ((data->'author'->>'first_name')); INSERT INTO books VALUES (4,'{ "name": "Book the Fourth","last_name": "Davis" } }'); ERROR: duplicate key value violates unique constraint "books_author_first_name" DETAIL: Key (((data -> 'author'::text) ->> 'first_name'::text))=(Charles) already exists.



Expression indexes are somewhat expensive to create,but once in place will make querying on any JsON property very fast.

A real world example

OK,let’s give this a go with a real life use case. Let’s say we’re tracking analytics,so we have aneventstable:


CREATE table events ( name varchar(200),visitor_ID varchar(200),propertIEs Json,browser Json );



We’re going to store events in this table,like pagevIEws. Each event has propertIEs,which Could be anything (e.g. current page) and also sends information about the browser (like OS,screen resolution,etc). Both of these are completely free form and Could change over time (as we think of extra stuff to track).

Let’s insert a couple of events:


INSERT INTO events VALUES ( 'pagevIEw','1','{ "page": "/" }','{ "name": "Chrome","os": "Mac","resolution": { "x": 1440,"y": 900 } }' ); INSERT INTO events VALUES ( 'pagevIEw','2','{ "name": "firefox","os": "windows","resolution": { "x": 1920,"y": 1200 } }' ); INSERT INTO events VALUES ( 'pagevIEw','{ "page": "/account" }',"y": 900 } }' ); INSERT INTO events VALUES ( 'purchase','5','{ "amount": 10 }',"resolution": { "x": 1024,"y": 768 } }' ); INSERT INTO events VALUES ( 'purchase','15','{ "amount": 200 }',"resolution": { "x": 1280,"y": 800 } }' ); INSERT INTO events VALUES ( 'purchase','{ "amount": 500 }',"y": 800 } }' );



Hm,this is starting to remind me of MongoDB!

Collect some stats

Using the JsON operators,combined with Traditional Postgresqlaggregate functions,we can pull out whatever we want. You have the full might of an RDBMS at your disposal.

browser usage?

SELECT browser->>'name' AS browser,count(browser) FROM events GROUP BY browser->>'name'; browser | count ---------+------- firefox | 3 Chrome | 2 




Total revenue per visitor?

SELECT visitor_ID,SUM(CAST(propertIEs->>'amount' AS integer)) AS total FROM events WHERE CAST(propertIEs->>'amount' AS integer) > 0 GROUP BY visitor_ID; visitor_ID | total ------------+------- 5 | 10 15 | 700 




Average screen resolution?

SELECT AVG(CAST(browser->'resolution'->>'x' AS integer)) AS wIDth,AVG(CAST(browser->'resolution'->>'y' AS integer)) AS height FROM events; wIDth | height -----------------------+---------------------- 1397.3333333333333333 | 894.6666666666666667 




You’ve probably got the IDea,so I’ll leave it here.

总结

以上是内存溢出为你收集整理的What can you do with PostgreSQL and JSON?全部内容,希望文章能够帮你解决What can you do with PostgreSQL and JSON?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/1175918.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-02
下一篇 2022-06-02

发表评论

登录后才能评论

评论列表(0条)

保存