SlideShare a Scribd company logo
PostgreSQL’s Secret
NoSQL Superpowers
Amanda Gilmore
Postgres supports several
document data formats.
Formats
XML
hstore
json
jsonb
How do you choose?
Do you wrap a foreign database?
How do you choose?
Do you have a (fairly) standard object schema with weird objects?
How do you choose?
Are you worried about lock contention?
XML
http://www.postgresql.org/docs/9.5/static/functions-xml.html
Schema
CREATE TABLE xml_samples (
id bigserial PRIMARY KEY,
documents xml,
comments text
)
Create
INSERT INTO xml_samples (documents, comments) VALUES (
XMLPARSE( DOCUMENT $$<?xml version="1.0"?>
<catalog>
...
</catalog>$$)
, 'This is an entire XML document')
Create
--Alternatively, this inserts one node per row
INSERT INTO xml_samples (documents, comments) VALUES (
$$<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</book>$$
, 'one book per row, as an XML node')
Read
--Gets all titles in the table
SELECT xpath('//book/title', documents) FROM xml_samples
--Gets all info on a book by title
SELECT * FROM xml_samples WHERE (xpath('//book/title/text()'
, documents))[1]::text = 'Midnight Rain'::text
Update
Cannot do this natively.
hstore
http://www.postgresql.org/docs/9.5/static/hstore.html
Schema
CREATE EXTENSION hstore
CREATE TABLE hstore_samples (
id bigserial PRIMARY KEY,
documents hstore,
comments text
)
Create
INSERT INTO hstore_samples (documents, comments)
VALUES ('"active_resource"=>"true"
,"resource_name"=>"swimming-swiftly-1234"
,"resource_size_in_mb"=>"30"
,"resource_created_at"=>"2016-03-14 17:20:47.216862"'
, 'this is a straight up K/V hash')
Read
--hstores are strings under the hood and require casting
SELECT * from hstore_samples
WHERE (documents -> 'resource_size_in_mb')::int > 30
Read
--You can get all of the values for a certain key:
SELECT (documents -> 'resource_name')::text
FROM hstore_samples
--or convert the entire table to an hstore:
SELECT hstore(t) FROM hstore_samples AS t
Read
--Pulling multiple values from the document
SELECT (documents -> 'resource_name')::text
, (documents -> 'active_resource')::text
FROM hstore_samples
Update
--Cannot do this in place , hence the || operator
UPDATE hstore_samples
SET documents = documents || '"active_resource"=>"false"'::hstore
WHERE documents @> '"resource_name"=>"swimming-swiftly-1234"'::hstore
json & jsonb
http://www.postgresql.org/docs/9.5/static/datatype-json.html
Read
--get json object. Array element by index (int) or by key
(str)
->
--get json object *by text*
->>
--containment operator, used to get an object by path
@>
--checks for existence of a key
?
http://www.postgresql.org/docs/9.5/static/functions-json.html
Schema
CREATE TABLE json_samples (
id bigserial PRIMARY KEY,
text_json json,
binary_json jsonb,
notes text
)
Create
INSERT INTO json_samples (text_json, notes) VALUES (
'{
"minStartTimeNs": "1429828653617000000",
"maxEndTimeNs": "1429839639367000000",
"dataSourceId":
"derived:com.google.heart_rate.bpm:com.google.android.gms:merge_heart_rate_bpm"
}'
, 'This is in the text json field')
Read
--Can check top-level keys before querying:
SELECT jsonb_object_keys(binary_json) FROM json_samples
--Well formed JSON path:
['point'][0]['value'][0]['fpVal']
--And you can extract specific values from the document:
SELECT binary_json->'point'->0->'value'->0->'fpVal' FROM json_samples
--Can check if a given key is present:
SELECT * FROM json_samples WHERE text_json::jsonb ? 'dataSourceId'
SELECT * FROM json_samples WHERE binary_json ? 'dataSourceId'
--And can check if the value of the key matches something:
SELECT * FROM json_samples
WHERE binary_json ->> 'minStartTimeNs' = '1429828653617000000'
Read
Update
--Can update at top level:
UPDATE json_samples
SET binary_json = binary_json || '{"address": {
"streetAddress": "123 Test Street",
"city": "Oakland",
"state": "CA",
"postalCode": "94123"
} }'
WHERE binary_json ->> 'lastName' = 'Gilmore'
Update
--or use jsonb_set() to drill down the tree:
SELECT jsonb_set(binary_json::jsonb
, '{address, streetAddress}'
, '"456 Lorem Ipsum St"'::jsonb)
FROM json_samples
WHERE binary_json ->> 'lastName' = 'Gilmore'
tl;dr
xml Can query on xpath Can’t update
hstore Can index keys Text, less performant
json Richly nested data Text, less performant
jsonb Nested data, fast reads Higher cost writes
xml: http://www.postgresql.org/docs/9.5/static/functions-xml.html
hstore: http://www.postgresql.org/docs/9.5/static/hstore.html
json & jsonb: http://www.postgresql.org/docs/9.5/static/functions-json.html
Source for the xml sample: https://msdn.microsoft.com/en-
us/library/ms762271(v=vs.85).aspx
Sample code for this talk on GitHub:
https://github.com/mandagill/PGConfUS_2016_syntax_samples
Links & References
Links & References
Questions?
Thanks, y’all!
amanda@heroku.com
GitHub: mandagill

More Related Content

DOCX
Format xls sheets Demo Mode
ODP
Indexed db
PDF
Dev Jumpstart: Build Your First App with MongoDB
ODP
2011 Mongo FR - Indexing in MongoDB
PPTX
Get docs from sp doc library
PPTX
Sequelize
PDF
DBIx::Class walkthrough @ bangalore pm
PPTX
Learn PHP Lacture2
Format xls sheets Demo Mode
Indexed db
Dev Jumpstart: Build Your First App with MongoDB
2011 Mongo FR - Indexing in MongoDB
Get docs from sp doc library
Sequelize
DBIx::Class walkthrough @ bangalore pm
Learn PHP Lacture2

What's hot (20)

PDF
wtf is in Java/JDK/wtf7?
PPT
Introduction to MongoDB
PPT
XML - State of the Art
DOC
Ex[1].3 php db connectivity
PPTX
Cassandra 2.2 & 3.0
PPTX
MS SQL Database basic
PPTX
MUC - Moodle Universal Cache
PDF
Softshake - Offline applications
PDF
MongoDB and RDBMS
PDF
Brief introduction of Slick
PPT
Zend framework 03 - singleton factory data mapper caching logging
TXT
Threading
PDF
BITS: Introduction to relational databases and MySQL - SQL
PDF
Mongo db for C# Developers
PDF
Mongo db for c# developers
PPTX
Introduction to the new official C# Driver developed by 10gen
PDF
Building Go Web Apps
PPTX
19. CodeIgniter imagini in mysql
PDF
Productive Programming in Groovy
PDF
Cassandra rapid prototyping with achilles
wtf is in Java/JDK/wtf7?
Introduction to MongoDB
XML - State of the Art
Ex[1].3 php db connectivity
Cassandra 2.2 & 3.0
MS SQL Database basic
MUC - Moodle Universal Cache
Softshake - Offline applications
MongoDB and RDBMS
Brief introduction of Slick
Zend framework 03 - singleton factory data mapper caching logging
Threading
BITS: Introduction to relational databases and MySQL - SQL
Mongo db for C# Developers
Mongo db for c# developers
Introduction to the new official C# Driver developed by 10gen
Building Go Web Apps
19. CodeIgniter imagini in mysql
Productive Programming in Groovy
Cassandra rapid prototyping with achilles
Ad

Viewers also liked (20)

PPTX
Charlene Ygoña
PPTX
Wekerle CIHR Team - Trauma Profiles and Correlates Among Maltreated Adolesce...
PDF
BOS-BOF MONTHLY REPORT -MARCH 2016
PDF
LESER-Safety-Valve-Compact-Performance-Extended-Catalog-EN
PPTX
Pearson y de Sperman
PPT
Educational Achievement among Child Welfare Youth: The Maltreatment and Adole...
PDF
ComputerWorld Intervju
PPT
Resiliency among Child Welfare Youth: Findings from The Maltreatment and Adol...
PPTX
Wekerle CIHR Team - CAPHC - The Maltreatment and Adolescent Pathways (MAP) Re...
PPT
Presentació pastors final
DOCX
Mithran j cv21316
PDF
Critical_Service_Catalog_EN
PPTX
Presentación1
PPT
CONSIDERATIONS FROM THE MALTREATMENT AND ADOLESCENT PATHWAYS (MAP) LONGITUDIN...
PPT
The linkages among childhood maltreatment, adolescent mental health, and self...
PDF
القانون الجنائي
PPTX
SES Lighting Parking Garage LED Installation
PDF
Mid-Jersey Business March 2016
DOCX
Mithran J CV21316
ODP
Dez illas máis bonitas
Charlene Ygoña
Wekerle CIHR Team - Trauma Profiles and Correlates Among Maltreated Adolesce...
BOS-BOF MONTHLY REPORT -MARCH 2016
LESER-Safety-Valve-Compact-Performance-Extended-Catalog-EN
Pearson y de Sperman
Educational Achievement among Child Welfare Youth: The Maltreatment and Adole...
ComputerWorld Intervju
Resiliency among Child Welfare Youth: Findings from The Maltreatment and Adol...
Wekerle CIHR Team - CAPHC - The Maltreatment and Adolescent Pathways (MAP) Re...
Presentació pastors final
Mithran j cv21316
Critical_Service_Catalog_EN
Presentación1
CONSIDERATIONS FROM THE MALTREATMENT AND ADOLESCENT PATHWAYS (MAP) LONGITUDIN...
The linkages among childhood maltreatment, adolescent mental health, and self...
القانون الجنائي
SES Lighting Parking Garage LED Installation
Mid-Jersey Business March 2016
Mithran J CV21316
Dez illas máis bonitas
Ad

Similar to PostgreSQL's Secret NoSQL Superpowers (20)

PDF
NoSQL Best Practices for PostgreSQL / Дмитрий Долгов (Mindojo)
PDF
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
PDF
NoSQL on ACID - Meet Unstructured Postgres
 
PDF
NoSQL and Spatial Database Capabilities using PostgreSQL
 
PDF
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
PDF
Mathias test
PPTX
PostgreSQL as NoSQL
PPTX
PostgreSQL 9.4 JSON Types and Operators
PDF
No sql way_in_pg
PDF
PostgreSQL, your NoSQL database
PDF
NoSQL store everyone ignored - Postgres Conf 2021
PDF
Pg no sql_beatemjoinem_v10
PDF
Postgres NoSQL - Delivering Apps Faster
 
PPT
The NoSQL Way in Postgres
 
PPT
Do More with Postgres- NoSQL Applications for the Enterprise
 
PDF
PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...
PDF
Oh, that ubiquitous JSON !
PPTX
Power JSON with PostgreSQL
 
PDF
NoSQL Now: Postgres - The NoSQL Cake You Can Eat
PDF
Working with JSON Data in PostgreSQL vs. MongoDB
NoSQL Best Practices for PostgreSQL / Дмитрий Долгов (Mindojo)
Postgres vs Mongo / Олег Бартунов (Postgres Professional)
NoSQL on ACID - Meet Unstructured Postgres
 
NoSQL and Spatial Database Capabilities using PostgreSQL
 
Webscale PostgreSQL - JSONB and Horizontal Scaling Strategies
Mathias test
PostgreSQL as NoSQL
PostgreSQL 9.4 JSON Types and Operators
No sql way_in_pg
PostgreSQL, your NoSQL database
NoSQL store everyone ignored - Postgres Conf 2021
Pg no sql_beatemjoinem_v10
Postgres NoSQL - Delivering Apps Faster
 
The NoSQL Way in Postgres
 
Do More with Postgres- NoSQL Applications for the Enterprise
 
PG Day'14 Russia, Работа со слабо-структурированными данными в PostgreSQL, Ол...
Oh, that ubiquitous JSON !
Power JSON with PostgreSQL
 
NoSQL Now: Postgres - The NoSQL Cake You Can Eat
Working with JSON Data in PostgreSQL vs. MongoDB

Recently uploaded (20)

PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PPT
JAVA ppt tutorial basics to learn java programming
PPTX
Presentation of Computer CLASS 2 .pptx
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
ISO 45001 Occupational Health and Safety Management System
DOCX
Looking for a Tableau Alternative Try Helical Insight Open Source BI Platform...
PPTX
Online Work Permit System for Fast Permit Processing
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
L1 - Introduction to python Backend.pptx
PPT
Introduction Database Management System for Course Database
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Materi-Enum-and-Record-Data-Type (1).pptx
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
PPTX
Transform Your Business with a Software ERP System
PPTX
Mini project ppt template for panimalar Engineering college
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Which alternative to Crystal Reports is best for small or large businesses.pdf
ManageIQ - Sprint 268 Review - Slide Deck
JAVA ppt tutorial basics to learn java programming
Presentation of Computer CLASS 2 .pptx
PTS Company Brochure 2025 (1).pdf.......
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
ISO 45001 Occupational Health and Safety Management System
Looking for a Tableau Alternative Try Helical Insight Open Source BI Platform...
Online Work Permit System for Fast Permit Processing
2025 Textile ERP Trends: SAP, Odoo & Oracle
VVF-Customer-Presentation2025-Ver1.9.pptx
L1 - Introduction to python Backend.pptx
Introduction Database Management System for Course Database
Softaken Excel to vCard Converter Software.pdf
Materi-Enum-and-Record-Data-Type (1).pptx
How Creative Agencies Leverage Project Management Software.pdf
FLIGHT TICKET RESERVATION SYSTEM | FLIGHT BOOKING ENGINE API
Transform Your Business with a Software ERP System
Mini project ppt template for panimalar Engineering college
Lecture 3: Operating Systems Introduction to Computer Hardware Systems

PostgreSQL's Secret NoSQL Superpowers

Editor's Notes

  • #2: -Who am I? Why do I care? => We use a lot of rich data stores on my team and querying gets complicated. I rather wish I had these slides when I started working heavily on PG. -Don’t worry about photoing slides, SQL is in GitHub -Assume I’m talking about 9.5 unless otherwise stated
  • #4: Do you want to put all the data in PG and format some fields as documents? Do you want to wrap a NoSQL DB? Here are some questions to ask that may help you come to an answer...
  • #5: Use the data format that maps your foreign data source Mongo -> json Redis -> hstore
  • #6: If your information *generally* maps to an object, likely easier to stay in PG entirely. E.g. car rental
  • #7: Are you worried about lock contention? -> You might have a single json blob in a field, but that row is always going to be locked when you’re performing some operation on it
  • #8: Yeaaaaaah xpaths RSS feeds amirite?
  • #11: Hstore values *must be a string*
  • #13: Asynchronous information processing is a possible use case here. I.e., stashing the API payload as soon as I get it and then processing it later in-application, queued process, etc.
  • #14: Available since 9.1 Contrib module Supports indexing, YEAH
  • #15: Contrib module, need to CREATE EXTENSION
  • #16: This is a basic string, but adding it into an hstore formatted field gives you the extra function-y goodness INSERT is nice and straightforward
  • #17: PG: You could have a B-Tree expression index on the expression "(documents -> 'resource_created_at')::timestamptz" here, which would let you use a b-tree index for the > operator here (Something GIN cannot do). HGMNZ: GIN indexes' support for hstore means that you can index all fields in an hstore with one index, which is quite unique as far as database functionality goes.
  • #21: PostgreSQL allows only one character set encoding per database. It is therefore not possible for the JSON types to conform rigidly to the JSON specification unless the database encoding is UTF8. Check with SHOW SERVER_ENCODING; Because the json type stores an exact copy of the input text, it will preserve semantically-insignificant white space between tokens, as well as the order of keys within JSON objects. Straight json - only when manipulating data at the application layer All the shiny operators work with jsonb jsonb - Supports indexing! :D LOCKS ARE STILL ROW LEVEL.
  • #22: The ->> is important; if I am matching on ‘Gilmore’ text, I need the ->> instead of the ->
  • #25: This is where it gets fun. :) Can query more deeply nested objects
  • #26: These are for top-level keys
  • #29: Here I’m going to verbally specify that with higher cost writes for jsonb, they are more expensive but reads are cheaper (much like you’d see for a normal column index in any case)